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. 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. The code above is supposed to print 2013. Thank you for your help.
Your approach to increment the year by 1 and check if the digits are distinct is correct, and your code is almost correct. 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. Move the line a = []
to after the line year += 1
and give it the proper indentation and your code will work. 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
:
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 = 1987
distinct = False
while not distinct:
year += 1
if len(set(str(year))) == len(str(year)):
distinct = True
print(year)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.