I am currently doing a problem on Kattis (https://open.kattis.com/problems/digits).
The task description is as follows:
Given any number x0, define a sequence using the following recurrence xi+1=the number of digits in the decimal representation of xi Your task is to determine the smallest positive i such that xi=xi−1.
I came up with code A initially, but after code A failed to meet the time limit, I tinkered around with the code slightly to reach code B.
Sample input
42
5
END
Sample output
3
2
Code A:
#time limit exceeded
def recurrence_index(prev):
counter = 1
while True:
current = len(str(prev))
if current == prev:
return counter
else:
counter += 1
prev = current
while True:
initial = input().strip()
if initial == 'END':
break
initial = int(initial)
print(recurrence_index(initial))
Code B:
def recurrence_index(prev):
counter = 2
while True:
current = len(str(prev))
if current == prev:
return counter
else:
counter += 1
prev = current
while True:
initial = input().strip()
if initial == 'END':
break
l = len(initial)
if l == 1 and int(initial) == 1:
print(1)
else:
print(recurrence_index(l))
Unfortunately, I am not quite sure why Code B is faster than Code A. It seems that I have arrived at the right answer by luck. If anyone can help explain why code B is faster than code A, your help will be greatly appreciated. Thank you!