Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert sort using cmp from python 2 to python 3?

I'm trying to convert this code which is written in python 2 to python 3

nums = ["30", "31"]
num.sort(cmp=lambda x, y: cmp(y + x, x + y))

Not sure how to do that in python 3 since cmp is removed (I believed)

The result should be ["31", "30"] instead of ["30", "31"]

like image 408
toy Avatar asked Jun 02 '16 23:06

toy


1 Answers

This is one of the rare cases where a comparator is much cleaner than a key function. I'd actually just reimplement cmp:

try:
    cmp
except NameError:
    def cmp(x, y):
        if x < y:
            return -1
        elif x > y:
            return 1
        else:
            return 0

and then use functools.cmp_to_key to convert the comparator to a Python 3 style key function:

nums.sort(key=functools.cmp_to_key(lambda x, y: cmp(y+x, x+y)))

For anyone wondering what this weird sort actually does, it finds the order in which to concatenate the input strings to produce the lexicographically greatest output string. When all the strings are sequences of digits, the output has the highest possible numeric value.

like image 118
user2357112 supports Monica Avatar answered Sep 19 '22 18:09

user2357112 supports Monica