Python最短距离点

时间:2016-02-25 16:30:35

标签: python

  

编写一个名为dist的函数,它接收两个点(因此每个列表包含两个元素),并计算它们之间的距离。在继续下一步之前,请确保这适用于以下示例   在dist内的嵌套循环中使用shortestDist,将点列表中的每个元素与列表中的每个元素进行比较。所以,基本上,找到列表中各点之间的最短距离。

这是我到目前为止所拥有的:

        sample= [[45, -99], [24, 83], [-48, -68], [-97, 99], [-8, -77], [-2, 50], [44, 41], [-48, -58], [-1, 53], [14, 86], [31, 94], [12, -91], [33, 50], [82, 72], [83, -90], [10, 78], [7, -22], [90, -88], [-21, 5], [6, 23]]

        def dist(p0, p1):
            return (((p0[0] - p1[0])**2) + ((p0[1] - p1[1])**2))**.5


        def shortestDist(sample):
            distances = []
            for i in range(len(sample)-1):
                for j in range(i+1, len(sample)):
                    distances += [dist(sample[i],sample[j])]
            return(min(distances))

找到两点之间的距离。我只需要一些帮助,找出如何开始编写shortestDist来比较所有点并跟踪最短距离。更新:错误已解决,我现在很高兴。感谢大家的帮助!

4 个答案:

答案 0 :(得分:1)

这应该做的工作

def shortestDist(points):
        sh = float("inf")
        for i in range(1, len(points)):
                d = dist(points[i-1], points[i])
                if d < sh:
                        sh = d
        return sh

答案 1 :(得分:1)

这是一个基于点列表的功能完备的示例。

points = [(1,5), (5,8), (8,1), (9,5)]

def euclideanDistance(coordinate1, coordinate2):
    return pow(pow(coordinate1[0] - coordinate2[0], 2) + pow(coordinate1[1] - coordinate2[1], 2), .5)

distances = []
for i in range(len(points)-1):
    for j in range(i+1, len(points)):
        distances += [euclideanDistance(points[i],points[j])]
print min(distances)

答案 2 :(得分:0)

我认为下面的代码会让你朝着正确的方向前进:

def shortestDist(points):
    min_dist = None
    while points:
        p1, p2 = points.pop()
        dist = dist(p1, p2)
        if min_dist is None:
            min_dist = dist
        else:
            min_dist = dist  if dist < min_dist else min_dist

如果您不了解代码的某些部分,请告诉我,我会给出更多解释。

祝你好运!

答案 3 :(得分:0)

首先,您可能希望使用元组而不是列表。无论哪种方式都可行,但考虑到价值&#34; x&#34;和&#34; y&#34;是不同的,虽然两个&#34;数字&#34; (double,int ...),通常使用元组。

您可以传递以下几点:

dist((0,1), (2,3))

可以像访问列表一样访问它们:

p0[0] # access "x" in point 0
p0[1] # access "y" in point 0

至于撰写shortestDistance,您需要从上面列出元组列表:例如[(0,1),(2,4),(3,2),(1,3)]

对于def来说是这样的事情:

def shortestDist(listOfPoints)

然后,对于每个点,您可以使用以下内容将其与每个点进行比较,然后将其存储在字典中。

 currentIndex = 0
 pointDict = {}
 for point in listOfPoints:
    currentPoint = point
    for i in range(currentIndex,len(listOfPoints)):
        pointDict[currentPoint] = dist(currentPoint,listOfPoints[i])

这应该让你开始。它假定这些点不重复。

相关问题