Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 外部for循环和内部if循环的时间复杂度_Python_Time Complexity - Fatal编程技术网

Python 外部for循环和内部if循环的时间复杂度

Python 外部for循环和内部if循环的时间复杂度,python,time-complexity,Python,Time Complexity,这里是tmp列表 res=[] for e in tmp: if not(e in res): res.append(e) 对于这段代码,时间复杂度是多少?为什么 for e in res: 这个循环是计算len(res)次的(我们称之为n) 在最坏的情况下,由于res最多可以有n个元素,搜索(因为res没有排序)也会被计算n次 res.append(e) append()方法的复杂度为O(1) 所以这个函数的复杂度是O(n^2) 如果您不必维护订单,您可以通过

这里是tmp列表

res=[]

for e in tmp:
    if not(e in res): 
        res.append(e)
对于这段代码,时间复杂度是多少?为什么

for e in res:
这个循环是计算len(res)次的(我们称之为n)

在最坏的情况下,由于res最多可以有n个元素,搜索(因为res没有排序)也会被计算n次

res.append(e)
append()方法的复杂度为O(1)

所以这个函数的复杂度是O(n^2)

如果您不必维护订单,您可以通过以下方式加快速度:

res = list(set(tmp))
如果有必要:

from ordered_set import OrderedSet
res = list(OrderedSet(tmp))

你认为时间复杂度是多少?为什么?你怎么能检查它呢?我投票决定结束这个问题,因为它实际上是一个计算机科学或数学问题,而不是一个编程问题。时间复杂度将有一个很大的O,N*N,但是这也可能是N*log(N),这取决于“res”的结构我们可以通过验证正在计算的循环数来检查这一点,我们知道N,因为我们循环了数组tmp中的每个值。那么由于res中元素的数量而增加的复杂性。既然res在开始时是空的,那么时间复杂性是否会是线性的?
from ordered_set import OrderedSet
res = list(OrderedSet(tmp))