如何使用嵌套循环来表示集合中两个坐标的距离



假设我有一组坐标,我需要找到任何点之间的最长距离,我该如何使用嵌套来实现这一点?

points = [[9, 10],
[4, 1],
[75, 23],
[93, 22],
[95, 98],
[99, 59],
[34, 87],
[83, 88],
[65, 42],
[0, 76]]

我对Python很生疏,但这里是我的解决方案:

import math
points = [[9, 10],
[4, 1],
[75, 23],
[93, 22],
[95, 98],
[99, 59],
[34, 87],
[83, 88],
[65, 42],
[0, 76]]
greatestDistance = 0
greatesPoint1 = [0,0]
greatesPoint2 = [0,0]
# Iterate through each coordinate on the list.
for currentPoint in range(len(points)):
# Measure the distance to each coorditane on the list AFTER the current one, so each distance is only measure once.
next = currentPoint + 1
for nextPoint in range(next, len(points)):
point1 = points[currentPoint]
point2 = points[nextPoint]
X1 = point1[0]
Y1 = point1[1]
X2 = point2[0]
Y2 = point2[1]
# The correct equation for measuring the distance between 2 points. (Can also apply to 3-D space by adding a 'Z' axis to each point and changing this equation accordingly.)
distance = math.sqrt((X1-X2)**2 + (Y1-Y2)**2) 
if greatestDistance < distance: 
greatestDistance = distance
greatesPoint1 = point1
greatesPoint2 = point2
# Return greatesDistance.
print("Greatest Distance = " + str(greatestDistance) + " From:" + str(point1) + " To:" + str(point2))

最新更新