Polygon Class: Finding area and length of Rectangle and Triangle

Viewed 177

I have been given the following code.

class Polygon:
    '''Class to represent polygon objects.'''

    def __init__(self, points):
        '''Initialize a Polygon object with a list of points.'''
        
        self.points = points

    def length(self):
        '''Return the length of the perimeter of the polygon.'''

        P = self.points
        
        return sum(sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)
                   for (x0, y0), (x1, y1) in zip(P, P[1:] + P[:1]))

    def area(self):
        '''Return the area of the polygon.'''
        
        P = self.points
        A = 0
        for (x0, y0), (x1, y1) in zip(P, P[1:] + P[:1]):
            A += x0 * y1 - y0 * x1
        return abs(A / 2)

I have to implement __init__ methods (and no other method) of two subclasses; Rectangle and Triangle such that a rectangle can be created by:

rectangle = Rectangle(width, height)

and a triangle by:

triangle = Triangle(a, b, c)

I have coded the Rectangle one with the following:

class Rectangle(Polygon):

    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.points = [(0,0), (0, height), (width, height), (width, 0)]

And the above code passes all the tests when input is only for Rectangle. However, I have trouble doing the same for Triangle. The input should be a, b and c where those are the side lengths of the triangle. I cannot figure out which points to use to generate the length and area of the Triangle:

class Triangle(Polygon):

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self.points = ??

I have tried all combinations of points using the side lengths, however, none are passing the test.

1 Answers

Have a look at: https://www.omnicalculator.com/math/triangle-height#how-to-find-the-height-of-a-triangle-formulas

h = 0.5 * ((a + b + c) * (-a + b + c) * (a - b + c) * (a + b - c))**0.5 / b
ac = (c**2 - h**2)**0.5
self.points = [
  (0, 0),
  (a, 0),
  (ac, h),  
]

enter image description here

By getting h and then applying Pythagoras' Theorem you are obtain the co-ordinates of the "third" point. The first two are trivial: the origin, and another point along one of the axes.

A minor point: instead of setting points directly it might be cleaner to call super().__init__(points).

Related