1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
from math import sqrt
class PointError(Exception): pass
class TriangleError(Exception): pass
class Point: def __init__(self, *args): if len(args) != 2: raise PointError("Need two coordinates, point not created.") if not isinstance(args[0], int) or not isinstance(args[1], int): raise PointError("Coordinates must be integers.") self.x = args[0] self.y = args[1]
def __repr__(self): return f"Point({self.x}, {self.y})"
def __str__(self): return f"Point of x-coordinate {self.x} and y-coordinate {self.y}"
class Triangle: def __init__(self, **kwargs): self.p1 = kwargs['point_1'] self.p2 = kwargs['point_2'] self.p3 = kwargs['point_3'] self.check_valid()
def check_valid(self): if self.is_collinear(): raise TriangleError("Incorrect input, triangle not created.")
def is_collinear(self): return (self.p2.y - self.p1.y) * (self.p3.x - self.p1.x) == (self.p3.y - self.p1.y) * (self.p2.x - self.p1.x)
@property def perimeter(self): side1 = self.calculate_distance(self.p1, self.p2) side2 = self.calculate_distance(self.p2, self.p3) side3 = self.calculate_distance(self.p3, self.p1) return side1 + side2 + side3
@property def area(self): a = self.calculate_distance(self.p1, self.p2) b = self.calculate_distance(self.p2, self.p3) c = self.calculate_distance(self.p3, self.p1) p = (a + b + c) / 2 return sqrt(p * (p - a) * (p - b) * (p - c))
def calculate_distance(self, p1, p2): return sqrt(((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2))
def change_point_or_points(self, **kwargs): flag=0 tmp_p1,tmp_p2,tmp_p3=self.p1,self.p2,self.p3 for key, value in kwargs.items(): if key == 'point_1': tmp_p1 = self.p1 self.p1 = value elif key == 'point_2': tmp_p2 = self.p2 self.p2 = value elif key == 'point_3': tmp_p3 = self.p3 self.p3 = value if self.is_collinear(): flag = 1 self.p1 = tmp_p1 self.p2 = tmp_p2 self.p3 = tmp_p3 if flag==1: print("Incorrect input, triangle not modified.")
|