簡體   English   中英

Kattis 'Digits' 問題:為什么我的第一組代碼超過了時間限制,但我的第二組沒有?

[英]Kattis 'Digits' question: Why does my first set of code exceed time limit, but my second set does not?

我目前在 Kattis 上做一個問題( https://open.kattis.com/problems/digits )。

任務描述如下:

給定任何數字 x0,使用以下遞歸定義一個序列 xi+1=xi 的十進制表示中的位數 你的任務是確定最小的正 i 使得 xi=xi-1。

我最初想出了代碼 A,但是在代碼 A 未能滿足時間限制后,我稍微修改了代碼以達到代碼 B。

樣本輸入

42
5
END

樣品 output

3
2

代碼 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))

代碼 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))

不幸的是,我不太確定為什么代碼 B 比代碼 A 快。看來我已經得到了正確的答案。 如果有人可以幫助解釋為什么代碼 B 比代碼 A 快,您的幫助將不勝感激。 謝謝!

在第一個代碼中, int(initial)在巨大的整數上是昂貴的,而這種努力被拋棄了,因為你最終只是在它上面調用 str(),這也可能是昂貴的。

在第二個代碼中,您只需直接調用len(initial) ,因此您只會在較小的整數(<= 100ish)上調用str() ,然后在那些更短的字符串上調用len()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM