gpt4 book ai didi

python - 我将如何使用嵌套循环来计算一组中两个坐标的距离?

转载 作者:太空宇宙 更新时间:2023-11-04 01:46:57 25 4
gpt4 key购买 nike

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

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

关于python - 我将如何使用嵌套循环来计算一组中两个坐标的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58896689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com