toy toy - 1 year ago 184
Python Question

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"]

Answer Source

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

except NameError:
    def cmp(x, y):
        if x < y:
            return -1
        elif x > y:
           return 1
            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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download