【发布时间】: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。抱歉
-
或
1023为999:)
标签: python python-3.x