heapq --- 堆積佇列 (heap queue) 演算法

原始碼: Lib/heapq.py


這個模組實作了堆積佇列 (heap queue) 演算法,亦被稱為優先佇列 (priority queue) 演算法。

Heap(堆積)是一顆二元樹,樹上所有父節點的值都小於等於他的子節點的值。使用陣列實作,對於所有從0開始的 k 都滿足 heap[k] <= heap[2*k+1]heap[k] <= heap[2*k+2] 。為了比較節點的值,不存在的元素被視為無限大。heap 存在一個有趣的性質:樹上最小的元素永遠會在根節點 heap[0] 上。

下方的 API 跟一般教科書的 heap queue 演算法有兩個方面不同:第一,我們的索引從 0 開始計算,這會父節點與子節點之間的關係產生很微小的差異,但更符合 Python 從 0 開始索引的設計。第二,我們的 pop 方法會回傳最小的元素而不是最大的元素 ( 在教科書中被稱作 "min heap",而 "max heap" 因為他很適合做原地排序,所以更常出現在教科書中 )。

這兩個特性使得把 heap 當作一個標準的 Python list 檢視時不會出現意外:heap[0] 是最小的物件,heap.sort() 能保持 heap 的性質不變!

建立一個 heap 可以使用 list 初始化為 [],或者使用函式 heapify() 將一個已經有元素的 list轉成一個 heap。

此模組提供下面的函式

heapq.heappush(heap, item)

item 放進 heap,並保持 heap 性質不變。

heapq.heappop(heap)

heap 取出並回傳最小的元素,同時保持 heap 性質不變。如果 heap 是空的會產生 IndexError 錯誤。只存取最小元素但不取出可以使用 heap[0]

heapq.heappushpop(heap, item)

item 放入 heap ,接著從 heap 取出並回傳最小的元素。這個組合函式比呼叫 heappush() 之後呼叫 heappop() 更有效率。

heapq.heapify(x)

在線性時間內將 list x 轉為 heap,且過程不會申請額外記憶體。

heapq.heapreplace(heap, item)

heap 取出並回傳最小的元素,接著將新的 item 放進heap。heap 的大小不會改變。如果 heap 是空的會產生 IndexError 錯誤。

這個一次完成的操作會比呼叫 heappop() 之後呼叫 heappush() 更有效率,並在維護 heap 的大小不變時更為適當,取出/放入的組合函式一定會從 heap 回傳一個元素並用 item 取代他。

函式的回傳值可能會大於被加入的 item 。如果這不是你期望發生的,可以考慮使用 heappushpop() 替代,他會回傳 heap 的最小值和 item 兩個當中比較小的那個,並將大的留在 heap 內。

這個模組也提供三個利用 heap 實作的一般用途函式

heapq.merge(*iterables, key=None, reverse=False)

合併多個已排序的輸入並產生單一且已排序的輸出(舉例:合併來自多個 log 檔中有時間戳記的項目)。回傳一個 iterator 包含已經排序的值。

sorted(itertools.chain(*iterables)) 類似但回傳值是一個 iterable ,不會一次把所有資料都放進記憶體中,並且假設每一個輸入都已經(由小到大)排序過了。

有兩個選用參數,指定時必須被當作關鍵字參數指定。

key 參數指定了一個 key function 引數,用來從每一個輸入的元素中決定一個比較的依據。預設的值是 None (直接比較元素)。

reverse is a boolean value. If set to True, then the input elements are merged as if each comparison were reversed. To achieve behavior similar to sorted(itertools.chain(*iterables), reverse=True), all iterables must be sorted from largest to smallest.

3.5 版更變: 加入選用參數 keyreverse

heapq.nlargest(n, iterable, key=None)

Return a list with the n largest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). Equivalent to: sorted(iterable, key=key, reverse=True)[:n].

heapq.nsmallest(n, iterable, key=None)

Return a list with the n smallest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). Equivalent to: sorted(iterable, key=key)[:n].

後兩個函式在 n 值比較小時有最好的表現。對於較大的 n 值,只用 sorted() 函式會更有效率。同樣地,當 n==1 時,使用內建函式 min()max() 會有更好的效率。如果需要重複使用這些函式,可以考慮將 iterable 轉成真正的 heap 。

基礎範例

A heapsort can be implemented by pushing all values onto a heap and then popping off the smallest values one at a time:

>>> def heapsort(iterable):
...     h = []
...     for value in iterable:
...         heappush(h, value)
...     return [heappop(h) for i in range(len(h))]
...
>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

雖然類似 sorted(iterable) ,但跟 sorted() 不同的是,這個實作不是 stable 的排序。

Heap 中的元素可以是 tuple 。這有利於將要比較的值(例如一個 task 的優先度)和主要資料放在一起排序。

>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'))
>>> heappush(h, (1, 'write spec'))
>>> heappush(h, (3, 'create tests'))
>>> heappop(h)
(1, 'write spec')

優先佇列 (Priority Queue) 實作細節

A priority queue is common use for a heap, and it presents several implementation challenges:

  • 排序的穩定性:你如何將兩個擁有相同 priority 的 task 按照他們被加入的順序回傳。

  • Tuple的排序在某些情況下會壞掉,例如當 Tuple (priority, task) 的 priorities 相等且 tasks 沒有一個預設的排序時。

  • 當一個 heap 中 task 的 priority 改變時,你如何將它移到 heap 正確的位置上。

  • 或者一個還沒被解決的 task 需要被刪除時,你要如何從佇列中找到並刪除指定的 task。

一個針對前兩個問題的解法是:儲存一個包含 priority 、 entry count 和 task 三個元素的 tuple 。兩個 task 有相同 priority 時, entry count 會讓兩個 task 能根據加入的順序排序。因為沒有任何兩個 task 擁有相同的 entry count ,所以永遠不會直接使用 task 做比較。

Another solution to the problem of non-comparable tasks is to create a wrapper class that ignores the task item and only compares the priority field:

from dataclasses import dataclass, field
from typing import Any

@dataclass(order=True)
class PrioritizedItem:
    priority: int
    item: Any=field(compare=False)

剩下的問題可以藉由找到要刪除的 task 並更改它的 priority 或者直接將它移除。尋找一個 task 可以使用一個 dictionary 指向佇列當中的 entry 。

移除 entry 或更改它的 priority 更為困難,因為這會破壞 heap 的性質。所以一個可行的方案是將原本的 entry 做一個標記表示它已經被刪除,並新增一個擁有新的 priority 的 entry 。

pq = []                         # list of entries arranged in a heap
entry_finder = {}               # mapping of tasks to entries
REMOVED = '<removed-task>'      # placeholder for a removed task
counter = itertools.count()     # unique sequence count

def add_task(task, priority=0):
    'Add a new task or update the priority of an existing task'
    if task in entry_finder:
        remove_task(task)
    count = next(counter)
    entry = [priority, count, task]
    entry_finder[task] = entry
    heappush(pq, entry)

def remove_task(task):
    'Mark an existing task as REMOVED.  Raise KeyError if not found.'
    entry = entry_finder.pop(task)
    entry[-1] = REMOVED

def pop_task():
    'Remove and return the lowest priority task. Raise KeyError if empty.'
    while pq:
        priority, count, task = heappop(pq)
        if task is not REMOVED:
            del entry_finder[task]
            return task
    raise KeyError('pop from an empty priority queue')

原理

Heap 是一個陣列對於所有從0開始的 index k 都存在性質 a[k] <= a[2*k+1]a[k] <= a[2*k+2] 。為了方便比較,不存在的元素被視為無限大。一個有趣的 heap 性質是 a[0] 永遠是最小的元素。

The strange invariant above is meant to be an efficient memory representation for a tournament. The numbers below are k, not a[k]:

                               0

              1                                 2

      3               4                5               6

  7       8       9       10      11      12      13      14

15 16   17 18   19 20   21 22   23 24   25 26   27 28   29 30

In the tree above, each cell k is topping 2*k+1 and 2*k+2. In a usual binary tournament we see in sports, each cell is the winner over the two cells it tops, and we can trace the winner down the tree to see all opponents s/he had. However, in many computer applications of such tournaments, we do not need to trace the history of a winner. To be more memory efficient, when a winner is promoted, we try to replace it by something else at a lower level, and the rule becomes that a cell and the two cells it tops contain three different items, but the top cell "wins" over the two topped cells.

If this heap invariant is protected at all time, index 0 is clearly the overall winner. The simplest algorithmic way to remove it and find the "next" winner is to move some loser (let's say cell 30 in the diagram above) into the 0 position, and then percolate this new 0 down the tree, exchanging values, until the invariant is re-established. This is clearly logarithmic on the total number of items in the tree. By iterating over all items, you get an O(n log n) sort.

A nice feature of this sort is that you can efficiently insert new items while the sort is going on, provided that the inserted items are not "better" than the last 0'th element you extracted. This is especially useful in simulation contexts, where the tree holds all incoming events, and the "win" condition means the smallest scheduled time. When an event schedules other events for execution, they are scheduled into the future, so they can easily go into the heap. So, a heap is a good structure for implementing schedulers (this is what I used for my MIDI sequencer :-).

Various structures for implementing schedulers have been extensively studied, and heaps are good for this, as they are reasonably speedy, the speed is almost constant, and the worst case is not much different than the average case. However, there are other representations which are more efficient overall, yet the worst cases might be terrible.

Heaps are also very useful in big disk sorts. You most probably all know that a big sort implies producing "runs" (which are pre-sorted sequences, whose size is usually related to the amount of CPU memory), followed by a merging passes for these runs, which merging is often very cleverly organised 1. It is very important that the initial sort produces the longest runs possible. Tournaments are a good way to achieve that. If, using all the memory available to hold a tournament, you replace and percolate items that happen to fit the current run, you'll produce runs which are twice the size of the memory for random input, and much better for input fuzzily ordered.

Moreover, if you output the 0'th item on disk and get an input which may not fit in the current tournament (because the value "wins" over the last output value), it cannot fit in the heap, so the size of the heap decreases. The freed memory could be cleverly reused immediately for progressively building a second heap, which grows at exactly the same rate the first heap is melting. When the first heap completely vanishes, you switch heaps and start a new run. Clever and quite effective!

In a word, heaps are useful memory structures to know. I use them in a few applications, and I think it is good to keep a 'heap' module around. :-)

註解

1

The disk balancing algorithms which are current, nowadays, are more annoying than clever, and this is a consequence of the seeking capabilities of the disks. On devices which cannot seek, like big tape drives, the story was quite different, and one had to be very clever to ensure (far in advance) that each tape movement will be the most effective possible (that is, will best participate at "progressing" the merge). Some tapes were even able to read backwards, and this was also used to avoid the rewinding time. Believe me, real good tape sorts were quite spectacular to watch! From all times, sorting has always been a Great Art! :-)