arr = [val] * N是否有衬里或恒定时间?

时间:2016-06-21 08:56:23

标签: python algorithm asymptotic-complexity

我正试图解决一些问题。 我想知道// convert to date object $scope.models.AppointmentDate = new Date($scope.models.AppointmentDate); var DateVal = $scope.models.AppointmentDate; DateVal = $filter('date')(DateVal , 'dd MMMM yyyy'); 是否有线性或恒定时间?

answ = [max] * N

列表A的长度为M. 因此,如果时间不变,我将收到算法的O(M)复杂度。 如果是线性的,我将收到O(M * N)复杂度。

2 个答案:

答案 0 :(得分:1)

由于您使用值N填充大小为max的数组,这意味着您正在执行N次写入 - 因此它的复杂性是线性的。 / p>

有些数据结构可以接收"默认"在绑定数组大小中未使用值显式声明的所有项的值。但是,Python的list()不是这样的结构。

答案 1 :(得分:1)

是。 CPython列表只是指针数组。在listobject.h中查看struct定义:

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