[英]Kattis 'Digits' question: Why does my first set of code exceed time limit, but my second set does not?
I am currently doing a problem on Kattis ( https://open.kattis.com/problems/digits ).我目前在 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.给定任何数字 x0,使用以下递归定义一个序列 xi+1=xi 的十进制表示中的位数 你的任务是确定最小的正 i 使得 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.我最初想出了代码 A,但是在代码 A 未能满足时间限制后,我稍微修改了代码以达到代码 B。
Sample input样本输入
42
5
END
Sample output样品 output
3
2
Code A:代码 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:代码 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.不幸的是,我不太确定为什么代码 B 比代码 A 快。看来我已经得到了正确的答案。 If anyone can help explain why code B is faster than code A, your help will be greatly appreciated.
如果有人可以帮助解释为什么代码 B 比代码 A 快,您的帮助将不胜感激。 Thank you!
谢谢!
In the first code, int(initial)
is expensive on huge huge integers, and that effort is thrown away because you eventually just call str() on it, which could also be expensive.在第一个代码中,
int(initial)
在巨大的整数上是昂贵的,而这种努力被抛弃了,因为你最终只是在它上面调用 str(),这也可能是昂贵的。
In the second code, you just directly call len(initial)
, so you are only ever calling str()
on small-ish integers (<= 100ish), and then calling len()
on those strings, which are even shorter.在第二个代码中,您只需直接调用
len(initial)
,因此您只会在较小的整数(<= 100ish)上调用str()
,然后在那些更短的字符串上调用len()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.