Sort a list to form the largest possible number

前端 未结 8 999
无人及你
无人及你 2020-11-27 20:29

I am trying to write a function that given a list of non negative integers, arranges them such that they form the largest possible number.

For example, given

相关标签:
8条回答
  • 2020-11-27 21:05

    The most straight-forward way is to use itertools.permutations() to model how you would solve this by hand:

    >>> from itertools import permutations, imap
    >>> a = [50, 2, 1, 9]
    >>> int(max(imap(''.join, permutations(map(str, a)))))
    95021
    
    0 讨论(0)
  • 2020-11-27 21:12
    import functools
    
    def cmpr(x, y):
        xy = str(x) + str(y)
        yx = str(y) + str(x)
        return -1 if (xy > yx) else 1
    
    a = [50, 2, 1, 9]
    a.sort(key=functools.cmp_to_key(cmpr))
    
    0 讨论(0)
提交回复
热议问题