有人可以解釋下一個循環的時間複雜度嗎?'if'in'時間複雜度
for x in iterable:
if x not in other_iterable:
return False
我找到了一個很好的Python的運行時間複雜文本講座here,看到了外for
循環時間爲O(N)。但是,if x not in other_iterable
如何影響時間複雜性?我想象循環將檢查x
對iterable
中的每個元素,直到找到,或者列表已用盡。那麼建議如何讓if x not in other_iterable
循環儘可能少的時間?可能已經整理了other_iterable
?我在理解時間複雜性方面幾乎是一個新手,並且想知道更多。
編輯:other_iterable
將是一個可能重複的列表。
這取決於。 'other_iterable'的數據類型是什麼?如果它是一個列表,它是O(N),但是如果它是一個集合,它是O(1)。 (所以整個循環是O(N^2)(O,NM)或O(N),取決於) –
@JoranBeasley不,它不是,交集仍然是O(N)。 (其中N是兩者中較小的一個) –
[Python中的\ *運算符中的\ *的複雜性]的可能重複(http://stackoverflow.com/questions/13884177/complexity-of-in-operator-in-python ) – Marat