【问题标题】:Python- Find nearest greater number with unique digitsPython-使用唯一数字查找最近的更大数字
【发布时间】:2020-06-23 18:59:52
【问题描述】:

我遇到了这个问题,您将从用户那里获取一个整数作为输入,然后返回最近的具有唯一数字的较大数字
首先,它看起来很简单,我编写了它的代码,它给了我想要的输出,但是对于某些输入,它返回一个具有重复数字的整数或一个具有比预期值更高的唯一数字,
我想知道为什么我的代码显示出与预期不同的行为,以及这个问题的正确答案是什么。 我也不知道当一个数字变成两位数时该怎么办如何使它独一无二,例如。 9999

  • 代码
    n = int(input("enter a no.:"))+1         #taking input adding 1 to make sure if the input is 
                                         #unique it should return higher no. with uniq 
    a =[]                                    #creating an empty list
    while n!=0:                              #loop to store digits in a list
        a.append(n%10)                       #at index 0 ones digit is stored
        n = int(n/10)                        #at index 1 tens digit is stored an so on...


    while len(set(a)) != len(a):             #checking if the list is unique
        for i in range(0,len(a)):            #
            occur = a.count(a[i])            #taking occurence of a list item
            if occur != 1:                   #if no. is repeated
                a[i]+=occur-1                #incrementing the repeating digit.

    a.reverse()                              #converting list to integer and printing
    n = 0
    for i in a:
        n = n*10+i
    print(n)
  • 行为
    1.为某些输入打印重复数字
    2.打印某些输入的值高于预期
    3.当一个数字变成两位数时。它把它当作一个数字来对待
  • 一些输出
enter a no.:1233  
output:  1234            #desired output: 1234

enter a no.:7885
output:  7896            #desired output: 7890

enter a no.:7886
output:  8008             #desired output: 7890

enter a no.:999
output:  2013             #desired output: 1023

【问题讨论】:

  • 我可能误解了这个问题,但为什么7885 的期望输出不是7890
  • 是的,你是对的,期望的输出应该是 7890。抱歉
  • 1023999 :)

标签: python python-3.x


【解决方案1】:

你自己可能把这复杂化了。

这样的事情会起作用而不是进行所有的转换吗?

n = int(input("enter a no.:"))+1   #taking input adding 1 to make 
                                   #sure if the input is unique then 
                                   #program does't return the input itself

a = str(n)                         # simply convert to a string

while len(set(a)) != len(a):       #checking if the string is unique
    n += 1
    a = str(n)

print(n)

【讨论】:

    【解决方案2】:

    为什么不简单地增加数字,直到找到具有唯一数字的数字?

    def next_uniq(n):
      a = str(n)  
      while len(set(a)) != len(a):
        a = str(int(a) + 1)
      return a
    
    for i in [1233, 7885, 7886, 999]:
      print(next_uniq(i))
    
    # 1234, 7890, 7890, 1023
    

    【讨论】:

    • 是的,我在发布问题后就明白了,现在我觉得很愚蠢,现在我把它弄得很复杂。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多