[英]'if not in' time complexity
有人可以解释以下循环的时间复杂度吗?
for x in iterable:
if x not in other_iterable:
return False
我在这里找到了一个非常好的Python操作时间复杂度文本讲座,并且看到外部for
循环的时间为O(N)。 但是, if x not in other_iterable
部分中如何影响时间复杂度? 我猜想循环将针对iterable
每个元素检查x
,直到找到它,或者列表用完为止。 那么, if x not in other_iterable
循环中if x not in other_iterable
可能要花费最短的时间, if x not in other_iterable
推荐的方法是什么? 可能已经对other_iterable
进行了other_iterable
? 我实际上是一位了解时间复杂性的菜鸟,并且想了解更多。
编辑: other_iterable
将是可能重复的列表。
在这个问题中,您称它们为iterable
因此我将假定它们未set
或相似,并且要确定x not inother_iterable
是否为真,您必须一次检查other_iterable
一个值。 例如,如果它们是列表或生成器,情况就是这样。
时间复杂度大约是最坏的情况。 这是一个上限 。 因此,在这种情况下,最糟糕的情况是iterable
中的所有内容都在other_iterable
但最后返回的是项目。 然后,对于iterable
的n
项目中的每一个,您将检查other_iterable
中的m
项目中的每一个,并且操作总数为O(n*m)
。 如果n
大小大致相同,则为O(n^2)
。
例如,如果iterable = [8, 8, 8]
other_iterable = [1, 2, 3, 4, 5, 6, 7, 8]
iterable = [8, 8, 8]
和other_iterable = [1, 2, 3, 4, 5, 6, 7, 8]
那么对于iterable
中的3个项目,您必须检查以下8个项目: other_iterable
直到您发现if
语句为false为止,这样总共可以进行8 * 3
次运算。
最好的情况是,如果iterable
的第一项不在other_iterable
。 然后,您将只检查iterable
的单个元素,但other_iterable
所有m
项目进行迭代,直到您了解if
条件为true并完成。 总共进行了m
操作。 但是,如上所述,big-O时间复杂度是最坏的情况,因此通常不会将其称为复杂度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.