[英]Simple query about time complexity for Python “in”
我有一個函數strip_punctuation(text),它接收一個文本字符串,並使用標點符號列表刪除其中的所有標點符號。 我不確定時間復雜度是O(N)* N還是O(N ^ 2)。 我認為這適用於N個文本長度為O(N),然后為標點符號長度為O(N)的情況。 有人可以澄清這段代碼的時間復雜度嗎?
def strip_punctuation(text):
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
stripped = ""
for i in text:
if i not in punctuations:
stripped = stripped + i
return stripped
如果N為len(text)
,則為O(N):
for i in text
如果M為len(punctuations)
,則此代碼為O(M ^ 2):
if i not in punctuations:
stripped = stripped + i
這是因為整個stripped
(長度> = M)必須被復制M次( stripped + i
構成stripped
的副本)。
因此,如果同時輸入了text
和punctuations
,則復雜度為O(N)* O(M ^ 2),但是在這種情況下,M為常數,因此復雜度為O(N) 。
請注意,如果punctuations
非常大,該函數將非常慢,但其復雜度仍僅為O(N),這僅意味着當輸入大N倍時,它的速度慢N倍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.