import queue
q = queue.Queue()
for i in range(1,10):
q.put(i)
K = int(input())
for k in range(K):
x =q.get()
last = x % 10
if last != 0:
q.put(10*x + last - 1)
q.put(10*x + last)
if last != 9:
q.put(10*x + last + 1)
print (x)
A new number of run-runs is generated by adding a number having a difference of 1 or less from the number of ones digit at the end from the number of run-runs from 1 to 9. Then, a new run-run number is generated from the generated run-run number. The process ends when the Kth run-run number is generated.
Storing all K run-run numbers in a list would mess up memory. Therefore, if you use a queue instead of a list, you can use the get function to expel the used run-run numbers that have been generated from the memory.
In this problem, it is necessary to distinguish between cases where the 1st place is 0, 9 or something else. I want to write the case as complete as possible. As far as embarrassing, I first wrote as follows.
if last==0:
q.put(10*x + last)
q.put(10*x + last + 1)
elif last==9:
q.put(10*x + last)
q.put(10*x + last - 1)
else:
q.put(10*x + last)
q.put(10*x + last - 1)
q.put(10*x + last + 1)
To prevent this from happening, you should be aware that you do not write the same process twice. If you think about when to perform a certain process instead of writing the process for a case, the code will naturally be beautiful.
Using queue saves memory! Case classification is processed-> Think about the flow of cases!
Recommended Posts