我需要实现一个函数,从给定的点集中,指定两个整数对返回点之间的平均距离。如果点集中少于2个点,则会引发ValueError异常。
距离使用以下公式计算:
d=sqrt((x1−x2)**2+(y1−y2)**2)
我正在努力让循环运行起来,但是它给了我一个错误,说types.Genericaliases没有len()方法。意识到这与输入为集合有关,但现在我不知道该如何解决:def average_distance(points: set[tuple[int,int]]) -> float:
from math import sqrt
points = list[input()]
list_dist =[]
for index in range(0, len(points)):
coordinate = points[index] # tuple in the set points
x1 = coordinate[0] # first el in the pair
y1 = coordinate[1] # second el in the pair
next_coordinate = points[index +1]
x2 = next_coordinate[0]
y2 = next_coordinate[1]
distance = math.sqrt(((x1-x2)**2)+((y1-y2)**2))
list_dist.append(distance)
total_dist = 0
for dist in distance:
total_dist += dist
avg_dist = total_dist//(len(distance))
return avg_dist
So
print (average_distance({(1,2), (3,4), (5,6)}))
预期输出:
3.7712
希望你能就此提供建议。
非常感谢。
avg_dist = total_dist//(len(distance))
-->avg_dist = total_dist//(len(list_dist))
- balderman