[英]Next Number with Distinct Digits CCC 2013 Senior 1
The 2013 CCC Senior 1 problem on page 4 is to find the smallest number that is larger than the input with distinct digits as the title explains. 如标题所述,第4页上的2013 CCC Senior 1问题是要找到最小的数字,该数字大于带有不同数字的输入。 I'm a total beginner at programming and I can't find what's wrong with this code: 我是编程的初学者,我找不到此代码出了什么问题:
year = 1987
distinct = 'no'
a = []
while distinct != 'yes':
year += 1
for i in str(year):
if i not in a:
a.append(i)
distinct = "yes"
else:
distinct = "no"
break
print(year)
I think the code is still in the while loop but I don't understand why. 我认为代码仍处于while循环中,但我不明白为什么。 The code above is supposed to print 2013. Thank you for your help. 上面的代码应该在2013年打印出来。谢谢您的帮助。
Your approach to increment the year by 1 and check if the digits are distinct is correct, and your code is almost correct. 您将年份加1并检查数字是否不同的方法是正确的,并且您的代码几乎是正确的。 Your mistake is that you initialize a[]
, your set of digits in the year, only once, but it should be initialized to empty for each year. 您的错误是您只将a[]
设置为年份中的一组数字,但是每年都应将其初始化为空。 Move the line a = []
to after the line year += 1
and give it the proper indentation and your code will work. 将行a = []
移到year += 1
并给它适当的缩进,您的代码将起作用。 That would make your code into: 那会使您的代码变成:
year = 1987
distinct = 'no'
while distinct != 'yes':
year += 1
a = []
for i in str(year):
if i not in a:
a.append(i)
distinct = "yes"
else:
distinct = "no"
break
print(year)
Another approach is to use a set, which automatically removes any duplicates. 另一种方法是使用集合,该集合将自动删除所有重复项。 You can check if making the string of the year into a set changes its size. 您可以检查是否将年份字符串设置为集合会更改其大小。 So perhaps use this, which also avoids using a status variable like distinct
: 因此,也许使用它,这也避免了使用诸如distinct
类的状态变量:
year = 1987
year += 1
while len(set(str(year))) != len(str(year)):
year += 1
print(year)
If you want that status variable, or do not like that repeated line year += 1
, you could do this: 如果您想要该状态变量,或者不喜欢重复的year += 1
,则可以执行以下操作:
year = 1987
distinct = False
while not distinct:
year += 1
if len(set(str(year))) == len(str(year)):
distinct = True
print(year)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.