[英]Why do two codes that calculate pi using the same algorithm have different running times?
[英]Why these two almost same codes have different efficient (Python)?
我當時正在用Python在leetcode上編程。
所以這就是問題所在: https : //leetcode.com/problems/reverse-vowels-of-a-string/
這是我的答案:
def reverseVowels(s):
result = list(s)
v_str = 'aeiouAEIOU'
v_list = [item for item in s if item in v_str]
v_list.reverse()
v_index = 0
for i, item in enumerate(s):
if item in v_list:
result[i] = v_list[v_index]
v_index+=1
return ''.join(result)
結果: Time Limit Exceeded
我在討論中發現了一個非常相似的答案:
def reverseVowels(s):
lst = list(s)
vowels_str = "aeiouAEIOU"
vowels_list = [item for item in lst if item in vowels_str]
vowels_list.reverse()
vowels_index = 0
for index, item in enumerate(lst):
if item in vowels_str:
lst[index] = vowels_list[vowels_index]
vowels_index += 1
return ''.join(lst)
結果:已Accepted
太奇怪了 我認為這兩個代碼看起來完全一樣。
它們的區別只不過是參數。
我很好奇為什么這些代碼會導致不同的結果。
兩種代碼之間有兩條不同的線。 第一個是:
在第一種情況下,它遍歷列表,而在第二種情況下,遍歷字符串。 這里可能會有一些性能損失,但這不是主要問題。
這是運行時間的來源。 在第一種情況下(工作代碼),它在由元音組成的字符串中尋找字符,該字符具有恆定的長度。 在第二種情況下,它將在字符串中包含的所有元音列表中查找字符,根據測試中給出的字符串,該字符可能很大。
在第一個的這些你遍歷字符串( s
)直接,多次。 在第二個列表中,轉換為列表后,將遍歷該列表( lst
)。
造成差異的確切原因是python解釋器中的一個實現細節(這非常大,對於正確性可能很重要)。
有關更多討論,請參見相關問題: 為什么迭代一小串字符串比一小串列表慢?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.