我得到了以下代码
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
和Triangle
这样可以通过以下方式创建矩形:
rectangle = Rectangle(width, height)
和一个三角形:
triangle = Triangle(a, b, c)
我用以下代码对Rectangle
进行了编码:
class Rectangle(Polygon):
def __init__(self, width, height):
self.width = width
self.height = height
self.points = [(0,0), (0, height), (width, height), (width, 0)]
当输入仅用于Rectangle
时,上述代码通过了所有测试。
然而,我在为Triangle
做同样的事情时遇到了困难。输入应该是a
、b
和c
,其中这些是三角形的边长。我无法确定要使用哪些点来生成Triangle
的长度和面积:
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
,然后应用毕达哥拉斯定理,就可以得到“第三”点的坐标。前两个是无关紧要的:原点和沿其中一个轴的另一个点一个小问题:与其直接设置
points
,不如调用super().__init__(points)
更干净相关问题 更多 >
编程相关推荐