Python "round robin"

Given several (x, y) ordered pairs, I want to compare the distances between each of them. So, pretend that I have a list of ordered pairs:

pairs = [a,b,c,d,e,f] 

I have a function that takes two ordered pairs and finds the distance between them:

 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 

How can I use this function to compare each ordered pair with every other ordered pair, ultimately finding two ordered pairs with the largest distance between them?

Psuedopsuedocode:

  distance(a,b) distance(a,c) ... distance(e,f) 

Any help would be greatly appreciated.

+4
source share
5 answers
 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 
+10
source

in python 2.6, you can use itertools.permutations

 import itertools perms = itertools.permutations(pairs, 2) distances = (distance(*p) for p in perms) 

or

 import itertools combs = itertools.combinations(pairs, 2) distances = (distance(*c) for c in combs) 
+17
source

Try:

 max(distance(a, b) for (i, a) in enumerate(pairs) for b in pairs[i+1:]) 

This avoids identity matching (e.g. distance(x, x) , distance(y, y) , etc.). It also avoids making symmetric comparisons, since distance(x, y) == distance(y, x) .


Update: I like the Evgeny solution to use itertools little better, as it expresses what you are trying to do more succinctly. Both of our solutions do the same. (Note: make sure you use combinations, not permutations - this will be much slower!)

+6
source

If you do not mind calculating the distance between two points that are the same twice, then the largest distance will be found:

 max( [distance(a, b) for a in pairs for b in pairs] ) 

Instead of using pairs a and b instead, follow these steps:

 import operator max( [((a,b), distance(a, b)) for a in pairs for b in pairs], key=operator.itemgetter(1)) 

You can combine this with John Feminella's decision to get a (a, b) tuple without making comparisons with extra distance

+3
source

a little connected, you do not need to calculate the Euclidean distance yourself, there math.hypot:

 In [1]: a = (1, 2) In [2]: b = (4, 5) In [3]: hypot(a[0]-b[0], a[1]-b[1]) Out[3]: 4.2426406871192848 
+3
source

All Articles