如何使用嵌套循环来计算一个集合中两个坐标的距离?

2024-05-29 02:59:22 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一组坐标,我需要找到任意点之间的最长距离,我将如何使用嵌套来进行这项工作?你知道吗

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

Tags: points长距离
1条回答
网友
1楼 · 发布于 2024-05-29 02:59:22

我对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))

相关问题 更多 >

    热门问题