Python列表是单链接还是双链接列表?

时间:2013-02-27 20:37:58

标签: python list complexity-theory singly-linked-list doubly-linked-list

我想知道使用append()构建Python v2.7列表的复杂程度是多少? Python列表是双重链接的,因此它是恒定的复杂性还是单独链接,因此是线性复杂性?如果它是单链接的,我如何在线性时间内从迭代中建立一个列表,该列表按照从开始到结束的顺序提供列表的值?

例如:

def holes_between(intervals):
  # Compute the holes between the intervals, for example:
  #     given the table: ([ 8,  9] [14, 18] [19, 20] [23, 32] [34, 49])
  #   compute the holes: ([10, 13] [21, 22] [33, 33])
  prec = intervals[0][1] + 1 # Bootstrap the iteration
  holes = []
  for low, high in intervals[1:]:
    if prec <= low - 1:
      holes.append((prec, low - 1))
    prec = high + 1
  return holes

1 个答案:

答案 0 :(得分:18)

python list.append()的时间复杂度为O(1)。请参阅Python Wiki上的Time Complexity list

在内部,python列表是指针的向量:

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;

根据需要调整ob_item向量的大小,以便为追加支付摊销的O(1)成本:

/* This over-allocates proportional to the list size, making room
 * for additional growth.  The over-allocation is mild, but is
 * enough to give linear-time amortized behavior over a long
 * sequence of appends() in the presence of a poorly-performing
 * system realloc().
 * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
 */
new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);

这使Python列表dynamic arrays