1
0
forked from tdwojak/Python2017
Python2017/labs04/task03.py
2017-12-14 12:28:39 +01:00

75 lines
2.1 KiB
Python

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import math
# klasa, która reprezentuje punkt w przestrzeni wielowymiarowej.
class Point:
# konstruktor, który ma przyjmyje tylko 1 parametr: listę współrzednych.
def __init__(self,coordinates=[]):
if self.is_numeric(coordinates):
self.coordinates = coordinates
else:
self.coordinates = None
# funkcja sprawdzająca czy lista składa się z samych liczb.
def is_numeric(self, lista):
bool = False
for i in lista:
bool = isinstance(i, int) or isinstance(i, float)
if not bool:
return False
return bool
# metoda, która dodaje dwa punkty po współrzędnych i zwróci obiekt typu 'Punkt'.
def __add__(self, other):
if len(self) == len(other):
return Point(map((lambda x,y: x+y), self.coordinates, other.coordinates))
else:
raise DimensionError("Dodawany punkt ma inny wymiar!")
# metoda zwracająca łancuch znakowy, który w czytelny sposób przedstawi punkt.
def to_string(self):
if self.coordinates == None:
return "()"
else:
return "(" + ", ".join(str(c) for c in self.coordinates) + ")"
# metoda, która zwróci liczbę współrzędnych punktu.
def __len__(self):
if self.coordinates is not None:
return len(self.coordinates)
else:
return 0
# metoda, która działa dokładnie tak samo jak metoda `to_string`.
def __str__(self):
return self.to_string()
# wyjątek `DimensionError`, który zostaje wyrzucony, jeżeli dodawany punkt ma inny wymiar.
class DimensionError(Exception):
def __init__(self, text="Błąd wymiaru!"):
self.text = text
def __str__(self):
return self.text
p_0 = Point([])
print(str(p_0))
print(len(p_0))
p_1 = Point([ 1, 3, 5])
print(p_1)
print(len(p_1))
p_2 = Point([ 1, 2, 4])
print(p_2)
print(len(p_2))
try:
p_sum = p_1.__add__(p_2)
print(p_sum)
print(len(p_sum))
#print(len(str(p_1.__add__(p_2))))
p_sum = p_0.__add__(p_1)
except Exception as ex:
print("Warning: {}".format(ex))