Reputation: 1627
Assuming you have a list of vectors- such as so:
myListOfVectors=[(10,2),(0,5),(3,2),(8,2),(9,5),(10,5]
What would be the quickest way to sort these vectors from small to large (assuming that the smallest distance from the origin would be the first member of the list and the second smallest distance would be the second member etc...)?
Upvotes: 0
Views: 4501
Reputation: 67197
def sqdist(vector)
return sum(x*x for x in vector)
myListOfVectors.sort(key=sqdist)
Results in:
>>> myListOfVectors
[(3, 2), (0, 5), (8, 2), (10, 2), (9, 5), (10, 5)]
I'm using the squared distance as you don't actually use the distance anywhere, and computing the square root is quite costly.
Upvotes: 5
Reputation: 9680
Assuming you are talking about Euclidean distance from origin, here's what I would do:
from math import sqrt
def euclidean_distance(v):
return sqrt(sum(x**2 for x in v))
myListOfVectors = [(10,2),(0,5),(3,2),(8,2),(9,5),(10,5)]
sorted(myListOfVectors, key=euclidean_distance)
Which returns
[(3, 2), (0, 5), (8, 2), (10, 2), (9, 5), (10, 5)]
This works on any n-dimensional set of vectors.
Upvotes: 1