Constructing the largest number possible by rearranging a list

前端 未结 8 732
后悔当初
后悔当初 2020-12-16 11:53

Say I have an array of positive whole integers; I\'d like to manipulate the order so that the concatenation of the resultant array is the largest number possible. For exampl

8条回答
  •  生来不讨喜
    2020-12-16 12:17

    import itertools
    nums =  ["9", "97", "13"]
    m = max(("".join(p) for p in itertools.permutations(nums)), key = int)
    

    You can use itertools.permutations as hinted and use the key argument of the max function (which tells which function to apply to each element in order to decide the maximum) after you concat them with the join function.

    It's easier to work with strings to begin with.

提交回复
热议问题