Help guys. I wrote a program to calculate the perimeter of the 6-gon. How it needs to be redone so that it can calculate the perimeter of any n-gon, where you need to enter n from the keyboard (and the program itself sets the coordinates of the points). How can I do that?

class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "point(" + str(self.x) + "," + str(self.y) + ")" class hexagon: def __init__(self, A, B, C, D, E, F): self.A = A self.B = B self.C = C self.D = D self.E = E self.F = F def __str__(self): r = "hexagon(" + str(self.A) + "," + str(self.B) + "," + str(self.C) + "," + str(self.D) + "," + str( self.E) + "," + str(self.F) + ")" return r def sides(self): AB = ((self.Bx - self.Ax) ** 2 + (self.By - self.Ay) ** 2) ** (1 / 2) BC = ((self.Cx - self.Bx) ** 2 + (self.Cy - self.By) ** 2) ** (1 / 2) CD = ((self.Dx - self.Cx) ** 2 + (self.Dy - self.Cy) ** 2) ** (1 / 2) DE = ((self.Ex - self.Dx) ** 2 + (self.Ey - self.Dy) ** 2) ** (1 / 2) EF = ((self.Fx - self.Ex) ** 2 + (self.Fy - self.Ey) ** 2) ** (1 / 2) FA = ((self.Ax - self.Fx) ** 2 + (self.Ay - self.Fy) ** 2) ** (1 / 2) return AB, BC, CD, DE, EF, FA def perim(self): a, b, c, d, e, f = self.sides() return a + b + c + d + e + f A = Point(0.0, 0.0) B = Point(0.0, 3.0) C = Point(4.0, 1.0) D = Point(5.0, 1.0) E = Point(6.0, 1.0) F = Point(7.0, 2.0) print(A.__str__(), B.__str__(), C.__str__(), D.__str__(), E.__str__(), F.__str__()) hx1 = hexagon(A, B, C, D, E, F) print(hx1.__str__()) print(hx1.sides()) print(hx1.perim()) 
  • def __init __ (self, * points)? And then calculate the lengths of the sides according to the coordinates of the ends of the segment. - my diamonds dancing

1 answer 1

Try, add the methods you need.

 from math import sqrt class Point: def __init__(self, x, y): self.x = x self.y = y class Hexagon: def __init__(self, *points): self.points = list(points) self.sides = list() self.perim() def perim(self): self.perim = 0 for i in range(len(self.points)): start = self.points[i - 1] end = self.points[i] side = sqrt((end.x - start.x)**2 + (end.y - start.y)**2) self.sides.append(side) self.perim += side a = Point(0, 0) b = Point(1, 1) c = Point(2, 0) ABC = Hexagon(a, b, c) print(ABC.perim)