我目前正在学习如何用Python编码,我遇到了这个任务,我正在try 解决它.但我想我在某个地方犯了一个错误,我想知道也许有人可以帮助我解决这个问题.任务是写一个代码,它将: 从文本文件导入四个2D坐标(A、B、C和X) 判断A、B、C是否可以是矩形的点 判断X是否在ABC矩形内 计算矩形的对角线.
到目前为止我有这个:
import math
def distance(point1, point2):
return math.sqrt((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2)
def is_rectangle(point1, point2, point3):
distances = [
distance(point1, point2),
distance(point2, point3),
distance(point3, point1)
]
distances.sort()
if distances[0] == distances[1] and distances[1] != distances[2]:
return True
else:
return False
def is_inside_rectangle(rectangle, point):
x_values = [vertex[0] for vertex in rectangle]
y_values = [vertex[1] for vertex in rectangle]
if (min(x_values) < point[0] < max(x_values)) and (min(y_values) < point[1] < max(y_values)):
return True
else:
return False
with open('coordinates.txt', 'r') as file:
coordinates = []
for line in file:
x, y = map(int, line.strip()[1:-1].split(','))
coordinates.append((x, y))
rectangle = [coordinates[0], coordinates[1], coordinates[2]]
diagonal1 = distance(coordinates[0], coordinates[2])
diagonal2 = distance(coordinates[1], coordinates[3])
if is_rectangle(coordinates[0], coordinates[1], coordinates[2]) and is_inside_rectangle(rectangle, coordinates[3]):
print("True")
print(f"Diagonal of the rectangle is: {max(diagonal1, diagonal2)}")
else:
print("False")
该代码有效,但我认为它计算对角线错误.例如,让我们将此点作为输入:A(0,0)、B(5,0)、C(0,5)和X(2,2).它说它们可以是矩形的点,对角线是5.当我把这些点写在纸上时,第四个点可以是D(5,5),然后对角线是7.07(50的平方根).或者它可以是D(-5,5),但它是一个对角线,一个对角线是5,但它不是最大值. 此外,我正在try 编写一个函数,该函数将判断文本文件中的所有数据是否都是integer.假设B是(m,k),那么它应该返回假,如果所有数据都是整数,那么继续执行代码.对此有什么 idea 吗?