python - arr = [val] * N 是否具有线性或常数时间?

标签 python algorithm asymptotic-complexity

我正试图在 codility 解决一些问题。 我想知道 answ = [max] * N 是否具有线性时间或常数时间?

def solution(N, A):

    answ = [0] * N
    max = 0

    for item in A:
        if item > N:
            answ = [max] * N # this line here. Linear or constant time ?
        else:
            answ[item-1] += 1

            if answ[item-1] > max:
                max = answ[item-1]

    return answ

列表 A 的长度为 M。 所以,如果时间是常数,我将得到 O(M) 复杂度的算法。 如果是线性的,我将得到 O(M*N) 复杂度。

最佳答案

是的。 CPython 列表只是指针数组。查看 listobject.h 中的结构定义:

https://hg.python.org/cpython/file/tip/Include/listobject.h#l22

typedef struct {
    PyObject_VAR_HEAD
    /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
    PyObject **ob_item;

    /* ob_item contains space for 'allocated' elements.  The number
     * currently in use is ob_size.
     * Invariants:
     *     0 <= ob_size <= allocated
     *     len(list) == ob_size
     *     ob_item == NULL implies ob_size == allocated == 0
     * list.sort() temporarily sets allocated to -1 to detect mutations.
     *
     * Items must normally not be NULL, except during construction when
     * the list is not yet visible outside the function that builds it.
     */
    Py_ssize_t allocated;
} PyListObject;

如果这还不能说服你......

In [1]: import time

In [2]: import matplotlib.pyplot as plt

In [3]: def build_list(N):
   ...:     start = time.time()
   ...:     lst = [0]*N
   ...:     stop = time.time()
   ...:     return stop - start
   ...: 

In [4]: x = list(range(0,1000000, 10000))

In [5]: y = [build_list(n) for n in x]

In [6]: plt.scatter(x, y)
Out[6]: <matplotlib.collections.PathCollection at 0x7f2d0cae7438>

In [7]: plt.show()

enter image description here

关于python - arr = [val] * N 是否具有线性或常数时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37939814/

相关文章:

python3 curses addstr in pad 未显示在迭代循环中

python - 根据列列表值过滤 pandas 数据框

algorithm - 如果某物是 f(n) 的小 O,它是否也是 f(n) 的大 O?

python - 多数组计算中cupy执行错误

python - 迭代由其他类组成的类

algorithm - 从背包中取回元素【一维数组实现】

algorithm - CART决策树算法中如何拆分连续属性?

python - 高效查找字符串是否包含一组字符(类似子串但忽略顺序)?

嵌套列表的Python递归求和大O分析

o(n) 的算法复杂度