Create a function that makes a greatest number from the digits of its input parameter
I'm a beginner in python so I need some help.
n = int(input("Enter a number: "))
def large(n):
a = n % 10
b = (n // 10) % 10
c = (n // 100) %10
d = (n // 1000) % 10
CodePudding user response:
I would just sort the string in descending order, then convert to an int
def largest(s):
return int(''.join(sorted(s, reverse=True)))
Some examples
>>> largest('123')
321
>>> largest('321')
321
>>> largest('102030')
321000
CodePudding user response:
Making the largest can be achieved by sorting the digits in descending order. You'll need to process variable number of digits so you integer division approach will not work. Also, if the user specifies leading zeros in his/her list of digits, they will be ignored because of the early conversion to int(). So the solution will require processing the input as a string before you convert the result to an integer.
Making the smallest is a little bit more subtle because you can't place the zeros at the start (they would disappear once converted to an int). The strategy would be to insert the zeros at the second position after sorting the other digits in ascending order.
For example:
s = input("Enter a number (largest): ")
n = int(''.join(sorted(s,reverse=True))) # descending order
print("largest:",n)
s = ''.join(sorted(s)) # ascending order
z = s.count('0') # number of zeros
n = int(s[z:z 1] s[:z] s[z 1:]) # insert zeros at 2nd position
print("smallest",n)
Sample Runs:
Enter a number (largest): 20430
largest: 43200
smallest 20034
Enter a number (largest): 090143
largest: 943100
smallest 100349