[英]python array time complexity?
array.array
和np.array
的.append
時間復雜度是多少?
我在python_wiki中看到list
、 collections.deque
、 set
和dict
的時間復雜度,但我找不到array.array
和np.array
的時間復雜度。 我在哪里可以找到它們?
因此,鏈接您提供的(也是一個TLDR ) list
在內部“表示為一個數組”鏈接它應該是 O(1),底部有一條注釋:
“這些操作依賴於“攤銷最壞情況”中的“攤銷”部分。個別操作可能需要非常長的時間,具體取決於容器的歷史記錄。 關聯
更多細節
它沒有 go 在文檔中詳細介紹,但是如果您查看源代碼,您實際上會看到發生了什么。 realloc
array
具有內部緩沖區,可以快速調整自身的大小,並在其增長/縮小時重新分配。
array.append
使用arraymodule.array_array_append
調用arraymodule.ins
調用arraymodule.ins1
是操作的肉和土豆。 順便說一下, array.extend
使用了它,但它只是提供Py_SIZE(self)
作為插入索引。
因此,如果我們閱讀arraymodule.ins1
中的注釋,它會從以下內容開始:
Bypass realloc() when a previous overallocation is large enough to accommodate the newsize. If the newsize is 16 smaller than the current size, then proceed with the realloc() to shrink the array.
...
This over-allocates proportional to the array 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, 34, 46, 56, 67, 79, ... Note, the pattern starts out the same as for lists but then grows at a smaller rate so that larger arrays only overallocate by about 1/16th -- this is done because arrays are presumed to be more memory critical.
了解array
數據結構以回答您的問題很重要。 由於兩個array
對象都基於 C arrays(常規, numpy ),它們共享許多相同的功能。
將一個項目添加到數組中的攤銷為O(1)
,但在大多數情況下,最終是O(n)
時間。 這是因為您的數組 object 可能尚未填充,因此將一些數據附加到 memory 中的該位置是一個相對微不足道的練習,它是O(1)
。 但是,在大多數情況下,數組已滿,因此需要在 memory 中完全復制並添加新項目。 這是一個非常昂貴的操作,因為需要復制一個n
大小的數組,從而進行插入O(n)
。
為了更清楚地說明這一點,請考慮因子為
2
且初始數組大小為1
的情況。 然后考慮復制成本以將數組從大小 1 增長到足夠大的位置,任何k >= 0
的 2^k+1 個元素。 這個大小是2^(k+1)
。 總復制成本將包括所有復制到 2 倍大的步驟:
1 + 2 + 4 + ... + 2^k = 2^(k+1) - 1 = 2n - 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.