繁体   English   中英

“如果不在”时间复杂度

[英]'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但最后返回的是项目。 然后,对于iterablen项目中的每一个,您将检查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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM