python 算法:Descending Order


Your task is to make a function that can take any non-negative integer as a argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.

Examples:

Input: 21445 Output: 54421
Input: 145263 Output: 654321

Input: 1254859723 Output: 9875543221


很傻的解法:

def Descending_Order(num):
    l=list(str(num))
    l.sort()
    l.reverse()
    n=int(''.join(l))
    return n

很好的解法:

def Descending_Order(num):
    return int("".join(sorted(str(num), reverse=True)))

字符串可以直接sorted,所以我爲啥當初非要換成列表??!!

【因爲sort()和sorted()這兩個函數用法是不同的,哎媽呀!】

sorted() 函數對所有可迭代的對象進行排序操作。
sort 與 sorted 區別:
sort 是應用在 list 上的方法,sorted 可以對所有可迭代的對象進行排序操作。(並返回新list)
list 的 sort 方法返回的是對已經存在的列表進行操作,而內建函數 sorted 方法返回的是一個新的 list,而不是在原來的基礎上進行的操作。


==================================智障的分割線================================

值得注意的是:

一、字符串轉化成list的命令是   list(字符串)

比如:

mmp='1234765'
mmp_list=list(mmp)
>>>mmp_list=['1','2','3','4','7','6','5']

二、把列表換成字符串的命令是   ''.join(list)

比如:

list=['1','3','2']
str_l=''.join(list)
>>>str_l='132'

其中,‘’中間可以加其他連接符,list也可以跟[:]表示範圍,如'-'.join(list[0:2])   就表示用-連接list裏前兩個元素。!!





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章