Python algorithm: 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


Silly solution:

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

Good solution:

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

[ Strings can be sorted directly, so why did I have to replace them with lists? ? ! !

[Because the usage of the two functions sort() and sorted() is different, oops!

The sorted() function sorts all iterable objects.
The difference between sort and sorted:
sort is a method applied to list, and sorted can sort all iterable objects . (And return a new list)
The sort method of list returns an operation on an existing list, while the built-in function sorted method returns a new list, not an operation on the original basis.


===================================The dividing line of mental retardation============ =====================

It is worth noting that:

1. The command to convert a string to a list is list (string)

for example:

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

2. The command to change the list to a string is ''.join(list)

for example:

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

Among them, other connectors can be added in the middle of '', and list can also be followed by [:] to indicate a range, such as '-'.join(list[0:2]), which means to use - to connect the first two elements in the list. ! !





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325455964&siteId=291194637