python - 多边形类:查找矩形和三角形的面积和长度
问题描述
我得到了以下代码。
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)]
上面的代码在 input 仅用于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 = 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),
]
通过获取h
然后应用毕达哥拉斯定理,您将获得“第三”点的坐标。前两个是微不足道的:原点和沿其中一个轴的另一个点。
一个小问题:points
与其直接设置,不如调用super().__init__(points)
.
推荐阅读
- xamarin - Xamarin Forms UWP ListView MouseHover 颜色
- java - Thymeleaf 和 SpringBoot 链接 Hfef 在单击链接时将 unicode 添加到 URL
- vue.js - VueJS - 在 href 属性中使用 mustache 模板字符串
- java - 如何写入android中数据目录之外的文件?
- html - 如何删除自定义复选框中的勾号?
- html - 引导文本框类“表单控件”的大小不会改变
- javascript - 动态更改悬停启用选项
- php - 测试用例设置功能中的 Laravel 5.8 宏
- javascript - Vuex - 更新数组内的整个对象
- keyboard - 如何使用自动热键使 F11 充当 ctrl+双击?