简体   繁体   English

创建一个函数,从其输入参数的数字中生成最小数字

[英]Create a function that makes a smallest number from the digits of its input parameter

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.我是 python 的初学者,所以我需要一些帮助。


n = int(input("Enter a number: "))

def large(n):
  a = n % 10
  b = (n // 10) % 10 
  c = (n // 100) %10
  d  = (n // 1000) % 10 

I would just sort the string in descending order, then convert to an int我只会按降序对字符串进行排序,然后转换为int

def largest(s):
    return int(''.join(sorted(s, reverse=True)))

Some examples一些例子

>>> largest('123')
321
>>> largest('321')
321
>>> largest('102030')
321000

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().此外,如果用户在他/她的数字列表中指定前导零,由于提前转换为 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).制作最小的有点微妙,因为您不能将零放在开头(一旦转换为 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM