|
| 1 | +priorityqueue.py |
| 2 | + |
| 3 | +Priority Queue Implementation with a O(log n) Remove Method |
| 4 | + |
| 5 | +This project implements min- amd max-oriented priority queues based on binary |
| 6 | +heaps. I found the need for a priority queue with a O(log n) remove method. |
| 7 | +This can't be achieved with any of Python's built in collections including |
| 8 | +the heapq module, so I built my own. The heap is arranged according to a given |
| 9 | +key function. |
| 10 | + |
| 11 | +Usage: |
| 12 | + >>> from priorityqueue import MinHeapPriorityQueue |
| 13 | + >>> items = [4, 0, 1, 3, 2] |
| 14 | + >>> pq = MinHeapPriorityQueue(items) |
| 15 | + >>> pq.pop() |
| 16 | + 0 |
| 17 | + |
| 18 | + A priority queue accepts an optional key function. |
| 19 | + >>> items = ['yy', 'ttttttt', 'z', 'wwww', 'uuuuuu', 'vvvvv', 'xxx'] |
| 20 | + >>> pq = MinHeapPriorityQueue(items, key=len) |
| 21 | + >>> pq.pop() |
| 22 | + 'z' |
| 23 | + >>> pq.pop() |
| 24 | + 'yy' |
| 25 | + |
| 26 | + Internally, the queue is a list of tokens of type 'Locator', which contain |
| 27 | + the priority value, the item itself, and its current index in the heap. |
| 28 | + The index field is updated whenever the heap is modified. This is what |
| 29 | + allows us to remove in O(log n). Appending an item returns it's Locator. |
| 30 | + >>> token = pq.append('a') |
| 31 | + >>> token |
| 32 | + Locator(value=1, item='a', index=0) |
| 33 | + >>> pq.remove(token) |
| 34 | + 'a' |
| 35 | + |
| 36 | + If we want to be able to remove any item in the list we can maintain an |
| 37 | + auxiliary dictionary mapping items to their Locators. Here's a simple |
| 38 | + example with unique items: |
| 39 | + >>> items = [12, 46, 89, 101, 72, 81] |
| 40 | + >>> pq = MinHeapPriorityQueue() |
| 41 | + >>> locs = {} |
| 42 | + >>> for item in items: |
| 43 | + ... locs[item] = pq.append(item) |
| 44 | + >>> locs[46] |
| 45 | + Locator(value=46, item=46, index=1) |
| 46 | + >>> pq.remove(locs[46]) |
| 47 | + 46 |
| 48 | + |
| 49 | + Iterating with 'for item in pq' or iter() will produce the items, not the |
| 50 | + Locator instances used in the internal representation. The items will be |
| 51 | + generated in sorted order. |
| 52 | + >>> items = [3, 1, 0, 2, 4] |
| 53 | + >>> pq = MinHeapPriorityQueue(items) |
| 54 | + >>> for item in pq: |
| 55 | + ... print(item) |
| 56 | + 0 |
| 57 | + 1 |
| 58 | + 2 |
| 59 | + 3 |
| 60 | + 4 |
0 commit comments