来自笛卡尔坐标的三角形



我是新手。我有一个三角形类,它接收 3 个格式为 [x, y] 的列表变量:abc。如何返回带有三角形笛卡尔点的字符串?

class Triangle():
def __init__(self, a, b, c):
"""
Constructor for Vec4
Expects points as arrays in the form of [x, y].
All coordinates are given as cartesian coordinates.
"""
self.a = a
self.b = b
self.c = c

def __str__(self):
"""
Returns a string representation of the triangle. The string is formatted as follows:
Point A: 0.00 0.00
Point B: 0.00 0.00
Point C: 0.00 0.00
"""
return ""

这是我的实现以及如何完成。您可以返回字符串,并记住将整数转换为字符串。

class Triangle():
def __init__(self, a, b, c):
"""
Constructor for Vec4
Expects points as arrays in the form of [x, y].
All coordinates are given as cartesian coordinates.
"""
self.a = a
self.b = b
self.c = c

def __str__(self):
"""
Returns a string representation of the triangle. The string is formatted as follows:
Point A: 0.00 0.00
Point B: 0.00 0.00
Point C: 0.00 0.00
"""
return "Point A: " + str(self.a[0]) + " " + str(self.a[1]) + "nPoint B: " + str(self.b[0]) + " " + str(self.b[1]) + "nPoint C: " + str(self.c[0]) + " " + str(self.c[1])
t = Triangle([5,4], [1,2], [7,9])
print(t)

输出:

Point A: 5 4
Point B: 1 2
Point C: 7 9

假设一个点是一个元组,如(1.5,6.7(

这是代码:

class Triangle():
def __init__(self, a, b, c):
"""
Constructor for Vec4
Expects points as arrays in the form of [x, y].
All coordinates are given as cartesian coordinates.
"""
self.a = a
self.b = b
self.c = c

def __str__(self):
"""
Returns a string representation of the triangle. The string is formatted as follows:
Point A: 0.00 0.00
Point B: 0.00 0.00
Point C: 0.00 0.00
"""
return f"Point A: {self.a[0]} {self.a[1]}nPoint B: {self.b[0]} {self.b[1]}nPoint C: {self.c[0]} {self.c[1]}"

您可以使用以下方法进行此操作:

t = Triangle((2.34,4.62), (6.7,8.52), (9.34,3.32))
print(t)

我建议添加一个新方法,该方法返回三角形单个点的表示形式。这样,您可以在__str__方法中使用它,并且代码将减少冗余和干净。

class Triangle():
def __init__(self, a, b, c):
"""
Constructor for Vec4
Expects points as arrays in the form of [x, y].
All coordinates are given as cartesian coordinates.
"""
self.a = a
self.b = b
self.c = c
def point_repr(self, p):
"""
Make a string representation of a point 'p', and return it.
p: list of the form [x, y].
"""
coords = "{0} {1}".format(*p)
# OR
coords = "{} {}".format(p[0], p[1])
return coords

def __str__(self):
"""
Returns a string representation of the triangle. The string is formatted as follows:
Point A: 0.00 0.00
Point B: 0.00 0.00
Point C: 0.00 0.00
"""
template = "Point {}: {}"
a = self.point_repr(self.a)
b = self.point_repr(self.b)
c = self.point_repr(self.c)
point_a = template.format("A", a)
point_b = template.format("B", b)
point_c = template.format("C", c)
formatted = "{}n{}n{}".format(point_a, point_b, point_c)
return formatted

相关内容

  • 没有找到相关文章

最新更新