Sort a list to form the largest possible number

前端 未结 8 1031
无人及你
无人及你 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: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))
    

提交回复
热议问题