Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of candidates according to a metric - Python?

I have a list of 2-D points

candidates = [(x1, y1), (x2, y2), (x3, y3), ...]

and a reference point ref = (x0, y0).

I now wish to sort the list candidates according to their euclidean distances from the reference point ref, in ascending order.

What is the most Pythonic way of doing so?

like image 222
Sibbs Gambling Avatar asked Dec 01 '22 03:12

Sibbs Gambling


2 Answers

Euclidean distance between two points (x1, y1) and (x2, y2) is given by:

sqrt((x1 - y1)^2 + (x2 - y2)^2))

To sort the list, you can use the formula, and also you can skip the sqrt part, as you are just doing comparison, and not calculating the actual distance. i.e:

if x > y then sqrt(x) > sqrt(y)

So, following would work:

ref = (x0, y0)
candidates = [(x1, y1), (x2, y2), (x3, y3), ...]

candidates.sort(key=lambda x: (x[0] - ref[0]) ** 2 + (x[1] - ref[1]) ** 2)
like image 74
Rohit Jain Avatar answered Dec 06 '22 17:12

Rohit Jain


Write a function to calculate euclidean distance and use that function with the key parameter of the list.sort function.

ref = (x0, y0)
def euclidean(coords):
    xx, yy = ref
    x, y = coords
    return ((x-xx)**2 + (y-yy)**2)**0.5

candidates = [(x1, y1), (x2, y2), (x3, y3), ...]
candidates.sort(key=euclidean)
like image 31
Ashwini Chaudhary Avatar answered Dec 06 '22 15:12

Ashwini Chaudhary