python - 多边形类 : Finding area and length of Rectangle and Triangle

标签 python class

我得到了以下代码。

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)

我必须实现两个子类的 __init__ 方法(并且没有其他方法); 矩形三角形,这样可以通过以下方式创建矩形:

rectangle = Rectangle(width, height)

和一个三角形:

triangle = Triangle(a, b, c)

我用以下代码对矩形进行了编码:

class Rectangle(Polygon):

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

当输入仅针对矩形时,上面的代码通过了所有测试。 但是,我对 Triangle 执行同样的操作时遇到困难。输入应为 abc,其中这些是三角形的边长。我无法弄清楚使用哪些点来生成三角形的长度和面积:

class Triangle(Polygon):

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

我已经尝试了使用边长的所有点组合,但是没有一个通过测试。

最佳答案

看看: 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

通过获取h,然后应用毕达哥拉斯定理,您将获得“第三”点的坐标。前两个很简单:原点和沿其中一个轴的另一个点。

一个小问题:调用 super().__init__(points) 可能会更干净,而不是直接设置 points

关于python - 多边形类 : Finding area and length of Rectangle and Triangle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67738437/

相关文章:

python - 在 Windows 上安装 rpy2

python - 在 python Pillow 中使用列表生成图像不起作用

python - create_string_buffer 抛出错误 TypeError : str/bytes expected instead of str instance

python - 袖扣(Plotly)无法绘制日期时间,但热图的 x 轴上的数字

python - Google App Engine 出现意外的 'site can' t 提供安全连接'错误

java - GUI 编程并从另一个类中调用一个类

java - 在多个类中使用一个对象

java - 类设计的最佳实践(子类+重写)

java - Oracle 非键字段上的唯一约束没有错误?

java - 在java中将类类型保存为Type数据类型