枚举的复杂性

时间:2015-06-30 00:17:57

标签: python arrays big-o time-complexity enumerate

我看到很多关于python内置方法的运行时复杂性的问题,并且很多方法都有很多答案(例如https://wiki.python.org/moin/TimeComplexity,{{3} },https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt等。)

我没有看到任何枚举的内容。我知道它至少返回一个新数组(索引),但生成它需要多长时间,而另一个数组只是原始数组?

换句话说,我假设它是用于创建新数组(迭代)的O(n)和用于重用原始数组的O(1)... O(n)in总(我认为)。副本的另一个O(n)是否为O(n ^ 2),或其他东西......?

3 个答案:

答案 0 :(得分:12)

enumerate-function返回一个迭代器。迭代器的概念描述为here

基本上这意味着迭代器初始化指向列表的第一项,然后每次调用next()方法时返回列表的下一个元素。

所以复杂性应该是:

初始化:O(1)

返回下一个元素:O(1)

返回所有元素:n * O(1)

请注意,枚举不会创建新的数据结构(元组列表或类似的东西)!它只是在现有列表上进行迭代,并牢记元素索引。

您可以自己尝试一下:

# First, create a list containing a lot of entries:
# (O(n) - executing this line should take some noticeable time)
a = [str(i) for i in range(10000000)] # a = ["0", "1", ..., "9999999"]

# Then call the enumeration function for a.
# (O(1) - executes very fast because that's just the initialization of the iterator.)
b = enumeration(a)

# use the iterator
# (O(n) - retrieving the next element is O(1) and there are n elements in the list.)
for i in b:
    pass  # do nothing

答案 1 :(得分:6)

假设天真的方法(枚举重复数组,然后迭代它),你有O(n)时间来复制数组,然后O(n)时间迭代它。如果那只是 n 而不是O(n),那么你将总共有2 * n 时间,但这不是O(n)的工作方式;所有你知道的是,它花费的时间将是 n 一些倍。这是(基本上)O(n)的意思,所以在任何情况下,枚举函数都是O(n)时间总和。

答案 2 :(得分:3)

正如马蒂诺指出的那样,enumerate()不会复制数组。相反,它返回一个用于迭代数组的对象。对enumerate()本身的调用是O(1)。

相关问题