I want to sort points in 2D coordinate system by their distance to the origin (0,0) in increasing order. I found this and tried something, but still I could not get desired result.
Here is my code:
from functools import cmp_to_key
def my_comp(point1, point2):
return point1[0]*point1[0] + point1[1]*point1[1] < point2[0]*point2[0] + point2[1]*point2[1]
points = [ [3.1, 4.1], [0.9, 0.8], [1.0, 1.0] ]
sorted(points, key=cmp_to_key(my_comp))
print(points)
Result:
[[3.1, 4.1], [0.9, 0.8], [1.0, 1.0]]
Expected:
[[0.9, 0.8], [1.0, 1.0], [3.1, 4.1]]
1) Your my_cmp()
function is supposed to return one of three values (+, -, or 0 depending upon the compare), but you only return two (True and False).
2) You ingnore the return value from sorted()
. sorted()
doesn't modify its argument, it returns a sorted copy of it.
3) Don't use cmp functions. They are hard to describe and hard to implement. Instead use key functions.
How about:
def my_key(point1):
return point1[0]*point1[0] + point1[1]*point1[1]
points = [ [3.1, 4.1], [0.9, 0.8], [1.0, 1.0] ]
points = sorted(points, key=my_key)
print(points)
assert points == [ [0.9, 0.8], [1.0, 1.0], [3.1, 4.1] ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With