Note that there are some explanatory texts on larger screens.

plurals
  1. POCan this cmp function be better written as a key for sorted()?
    text
    copied!<p>I was writing a solution to the problem of how to generate the maximum integer by rearranging then concatenating integers from a set. I was given that for the maximum integer, the arrangement of any two of its adjacent integers from the set when expressed as an integer is greater than the arrangement of them being swapped. i.e. given {98, 9}; the arrangement 998 is greater than 989. This holds for all the constituent integers in the examples given below.</p> <p>I needed to write some code that worked for Python 2.7 as well as 3.3 and came up with the following Python code:</p> <pre><code>try: cmp # Python 2 OK or NameError in Python 3 def maxnum(x): return ''.join(sorted((str(n) for n in x), cmp=lambda x,y:cmp(int(y+x), int(x+y)))) except NameError: # Python 3 from functools import cmp_to_key def cmp(x, y): return -1 if x&lt;y else ( 0 if x==y else 1) def maxnum(x): return ''.join(sorted((str(n) for n in x), key=cmp_to_key(lambda x,y:cmp(int(y+x), int(x+y))))) for numbers in [(1, 34, 3, 98, 9, 76, 45, 4), (54, 546, 548, 60)]: print('Numbers: %r\n Largest integer: %15s' % (numbers, maxnum(numbers))) </code></pre> <p>This gives output:</p> <pre><code>Numbers: (1, 34, 3, 98, 9, 76, 45, 4) Largest integer: 998764543431 Numbers: (54, 546, 548, 60) Largest integer: 6054854654 </code></pre> <p>Now Raymond Hettinger states that 'key=' is superior to 'cmp=' and I tend to agree with him, (before his Pycon 2013 talk <a href="https://www.youtube.com/watch?v=OSGv2VnC0go" rel="nofollow">"Transforming code into Beautiful, Idiomatic Python"</a>). My problem is that <strong>I haven't been able to solve the problem with a key function as elegant as the cmp function</strong>.</p> <p>Any ideas? Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload