Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sorting with "key" function insufficiencies

On one hand it is easy to see given a key function, one can easily implement a sort that does the same thing using a compare function. The reduction is as follows:

def compare(x,y):
    return key(x) - key(y)

On the other, how do we know for sure we are not losing potential sortings by restricting every kinds of sort by a map of elements using key? For instance, suppose I want to sort a list of length 2 tuples (x,y) where I insist the following compare method:

def compare(tup1,tup2):
    if (tup1[1] < tup2[0]):
       return -1
    if (tup1[0] % 2 == 0):
       return 1
    if (tup1[0] - tup2[1] < 4):
       return 0
    else:
       return 1

Now tell me how do I translate this compare into a corresponding "key" function such that my sorting algorithm proceed the same way? This is not a contrived example as these kinds of customised sorting show up in symmetry breaking algorithms during a search, and is very important.

like image 982
Evan Pu Avatar asked Sep 30 '26 08:09

Evan Pu


1 Answers

Use functools.cmp_to_key, this will guarantee the same sorting behavior as your compare function. The source for this function can be found on Python's Sorting How To document.

like image 178
Andrew Clark Avatar answered Oct 01 '26 20:10

Andrew Clark