Sort a list to form the largest possible number

前端 未结 8 1028
无人及你
无人及你 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条回答
  •  -上瘾入骨i
    2020-11-27 21:03

    I hope I'm not varying too much on this. My input is cast as a list of strings. I generate the list of permutations, creating a list of lists, and then sort the sublists from least to greatest. Finally, I take the last element of the sorted list.

    import itertools
    
    digits = ['50', '2', '1', '9']
    perms = itertools.permutations(digits)
    sorted_numlist = sorted(perms)
    print sorted_numlist[-1]
    

    If you'd rather have the number itself rather than the list of elements...

    import itertools
    
    digits = ['11', '68', '4', '12']
    perms = itertools.permutations(digits)
    numlist = []
    for sublist in perms:
        permutated_num = "".join(sublist)
        numlist.append(int(permutated_num))
    
    sorted_numlist = sorted(numlist)
    print sorted_numlist[-1]
    

    That second one actually also serves to show the the first is properly sorting on lists.

    I'm pretty new with Python and would appreciate comments/improvements.

提交回复
热议问题