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"]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With