toy
toy

Reputation: 12141

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

Upvotes: 7

Views: 3434

Answers (1)

user2357112
user2357112

Reputation: 280390

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.

Upvotes: 12

Related Questions