python - 我将如何使用嵌套循环来测量一组中两个坐标的距离?
问题描述
假设我有一组坐标,我需要找到任何点之间的最长距离,我将如何使用嵌套来做到这一点?
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))
推荐阅读
- google-maps-api-3 - 在谷歌地图 v3 Javascript 中重置标记图标
- javascript - PEGjs 可以将语句的“结束”字符作为输入吗?
- python - 使用 Python/Pandas 获取 Excel 列中的最大值并显示行名
- cuda - 等效于 CUDA 中的屏障(CLK_GLOBAL_MEM_FENCE)
- elasticsearch - logstash cmd没有运行
- android - react-native run-android => 无法解析配置 ':classpath' 的所有依赖项
- java - 如何返回上一个菜单?
- cocoa - 给子视图比父视图更高的优先级?
- python - 缩短 if、elif、elif else 子句
- batch-file - 批处理文件制作目录并复制到它