对于一组中两个坐标的最长距离,如何使用嵌套循环?

问题描述 投票:0回答:3

说我有一组坐标,我需要找到任何点之间的最长距离,如何使用嵌套进行此操作?

import math

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

def get_longest_trip(points):
    for cords in points:
        for i in cords:
          #not sure what exactly to add here


longestTrip = get_longest_trip(points)
print("The longest trip is ", longestTrip)

python nested-loops
3个回答
0
投票

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

1
投票

您可以在abs中使用列表理解

m = max(abs(a-b) for a,b in points)

您可以这样返回

def get_longest_trip(points):
   return max(abs(a-b) for a,b in points)

0
投票
distance = max([abs(n[0] - n[1]) for n in points])

这里使用嵌套循环是一个非常具体的要求,并且不是必需的-单个列表理解就足够了。

© www.soinside.com 2019 - 2024. All rights reserved.