Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.2 KiB

  1. import math
  2. # version with 2 separate functions
  3. def distance(p1, p2):
  4. return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  5. def perimeter(polygon):
  6. perimeter = 0
  7. points = polygon + [polygon[0]]
  8. for i in range(len(polygon)):
  9. perimeter += distance(points[i], points[i + 1])
  10. return perimeter
  11. # oop version with classes
  12. class Point:
  13. def __init__(self, x, y):
  14. self.x = x
  15. self.y = y
  16. def distance(self, p2):
  17. return math.sqrt((self.x - p2.x) ** 2 + (self.y - p2.y) ** 2)
  18. class Polygon:
  19. def __init__(self, points = []):
  20. self.vertices = []
  21. for point in points:
  22. if isinstance(point, tuple):
  23. # *point splits point into 2 parameters for Point.__init__()
  24. point = Point(*point)
  25. self.vertices.append(point)
  26. def add_point(self, point):
  27. self.vertices.append((point))
  28. def perimeter(self):
  29. perimeter = 0
  30. try:
  31. points = self.vertices + [self.vertices[0]]
  32. except IndexError:
  33. print("The polygon has no points.")
  34. else:
  35. for i in range(len(self.vertices)):
  36. perimeter += points[i].distance(points[i + 1])
  37. return perimeter