给定多个(x,y)有序对,我想比较每个对之间的距离。
所以假装我有一个有序对的列表:
pairs = [a,b,c,d,e,f]
我有一个函数,它需要两个有序对并找到它们之间的距离:
def distance(a,b):
from math import sqrt as sqrt
from math import pow as pow
d1 = pow((a[0] - b[0]),2)
d2 = pow((a[1] - b[1]),2)
distance = sqrt(d1 + d2)
return distance
如何使用此函数将每个有序对与其他所有有序对进行比较,最终找到它们之间距离最大的两个有序对?
伪伪代码:
distance(a,b)
distance(a,c)
...
distance(e,f)
任何帮助将不胜感激。
最佳答案
try:
from itertools import combinations
except ImportError:
def combinations(l, n):
if n != 2: raise Exception('This placeholder only good for n=2')
for i in range(len(l)):
for j in range(i+1, len(l)):
yield l[i], l[j]
coords_list = [(0,0), (3,4), (6,8)]
def distance(p1, p2):
return ( ( p2[0]-p1[0] ) ** 2 + ( p2[1]-p1[1] )**2 ) ** 0.5
largest_distance, (p1, p2) = max([
(distance(p1,p2), (p1, p2)) for (p1,p2) in combinations(coords_list, 2)
])
print largest_distance, p1, p2
关于Python "round robin",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/728543/