Question

So, when sorting a list in python, the sorted function can take a cmp keyword to override the __cmp__ function of the objects we are sorting.

I would expect max to have a similar keyword, but it doesn't. People know why?

And in any case, anyone know the most pythonic way to get around this? I don't want to override __cmp__ for the classes themselves, and other options I can think of like sorted(L,cmp=compare)[0] seem ugly. What would be a nice way to do this?

The actual example is given as L=[a1,a2,...,an] where each ak is itself a list of integers we want the maximum where ai<aj is in the lexicographical sense.

Was it helpful?

Solution

Don't use cmp. It has been removed from Python3 in favor of key.

Since Python compares strings lexicographically, you could use key = str to find the "maximum" integer:

In [2]: max([10,9], key = str)
Out[2]: 9
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top