Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom compare function in python3

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]]
like image 844
Eziz Durdyyev Avatar asked Mar 16 '18 18:03

Eziz Durdyyev


Video Answer


1 Answers

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] ]
like image 114
Robᵩ Avatar answered Sep 29 '22 07:09

Robᵩ