找到列表中任何一对点之间所有可能距离的最大值的最快方法是什么。

时间:2015-09-21 18:21:10

标签: python

我有一个列表l,其中包含n个点数。列表中的每个元素都是具有x坐标和y坐标的点。我试图找出最快捷的方法,我可以找到列表l中元素之间所有可能距离的最大值。

准确地说,让列表l

l = [(1,2),(5,3),(6,9)]

如果

d((1,2),(5,3)) = 1,  
d((5,3),(6,9)) = 2,  
d((6,9),(1,2)) = 5

其中d是我的距离函数,我的解决方案是5,它是列表中任意一对点之间所有可能距离的最大值。

我感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

要获得所有点的组合,您可以使用itertools

for p0, p1 in itertools.combinations(list, 2):
    print( d(p0,p1) )

将打印所有(本例中为三个)距离。找到最大左侧作为练习...

答案 1 :(得分:0)

>>> max(((i,j,dist(i,j)) for i,j in itertools.combinations(l, 2)), key=lambda x:x[2])
((5, 3), (6, 9), 13)

答案 2 :(得分:0)

你能用numpy和scipy吗? scipy.spatial.distance.cdist似乎做你想做的事。而且根据经验,即使有数十万个点也会非常快速地解决它,这基本上会扼杀纯粹的蟒蛇。

找出四个二维坐标之间的欧几里德距离:

>>> from scipy.spatial import distance
>>> coords = [(35.0456, -85.2672),
...           (35.1174, -89.9711),
...           (35.9728, -83.9422),
...           (36.1667, -86.7833)]
>>> dists = distance.cdist(coords, coords, 'euclidean')
>>> dists
array([[ 0.    ,  4.7044,  1.6172,  1.8856],
       [ 4.7044,  0.    ,  6.0893,  3.3561],
       [ 1.6172,  6.0893,  0.    ,  2.8477],
       [ 1.8856,  3.3561,  2.8477,  0.    ]])

要查找最大距离,您可以使用numpy的max功能。

>>> import numpy as np
>>> np.max(dists)
6.089281104531147

所以在你的情况下:

>>> l = [(1,2),(5,3),(6,9)]
>>> np.max(distance.cdist(l, l, "euclidean"))
8.602325267042626

不是5,但我猜你给d的结果赋予了任意值?