- Two kinds of priority queue implementation:
from queue import PriorityQueue
import heapq
- Heapq
Visit for details: https://docs.python.org/3/library/heapq.html
Heapq functions are directly applied to list. You can create a normal list, can convey it into functions in heapq package.
You can get the top element simply by heap[0].
Heapq uses min for top. You can negate them to maintain max for top.
heappush: O(log(n))
heappop: O(log(n)). Actually it first pop the last one of the list and then replace the top element with it and then siftup and siftdown.
heappushpop(heap, item): push then pop. Length does not change. O(log(n))
heapreplace(heap, item): pop then push. Length does not chagne. O(log(n))
heapify(list): transform a list to heap inplace. O(n) time complexity. (heap sort is O(nlog(n)) because you need to delete the top element one by one after building the heap). For a already arranged heap, if you heapify it, you will still sift up and sift down all the elements.
heapq.nlargest(n, iterable, key=None): find the n largest ones in a list.
heapq.nsmallest(n, iterable, key=None): find the n smallest ones in a list.
Deletion: if you want to delete a special position in the heap, you need to copy the siftup and siftdown function in the source code of heapq, and then use the last element to replace the special element, and then sift up and sift down it. But when u sift down it, you need to set the start position to be the root position because the last element may be smaller than the parent of the node you replace.
In heappop, siftup till the leaf first and then siftdown is better than classical heap sift because you only conduct one comparison in each sift (only compare two childs in siftup and only compare one child and parent in siftdown).
If you want to maintain a fixed length priority queue, you need to write codes to check whether the maximal length is reached. When it is reached, you can use heapq.pushpop() to add the new element.
- PriorityQueue
See for details: https://docs.python.org/3/library/queue.html
If you put item in a full PQ, or get item from a empty PQ, there will be block.
You cannot get the top element without pop.