heapq: a min-heap on a list you own
heapq does the same moves in C, on a plain list you own. Six things cover nearly every use:
heapq.heappush(h, item)andheapq.heappop(h): O(log n). Popping an empty heap raisesIndexError.h[0]: the smallest, without removing it. O(1).heapq.heapify(h): turns a list into a heap in place. O(n).heapq.heappushpop(h, item)pushes, then pops.heapq.heapreplace(h, item)pops, then pushes. Each does one sift instead of two, andheapreplacekeeps the size fixed, which suits a heap of size k. A pop and a push in the right order give the same result, so these two names are not worth memorizing.
It's a min-heap: heappop always returns the smallest.
Put a count after the priority, so a tie never compares the items
A heap compares items with <. Tuples compare field by field, so a (priority, thing) pair is ordered by its priority first. That's how you attach a priority to anything. But watch what a tie does:
h = [(30, {"id": "promo"})]
heapq.heappush(h, (30, {"id": "refund"}))
TypeError: '<' not supported between instances of 'dict' and 'dict'
Both priorities are 30, so the comparison moves on to the dicts, and dicts can't be compared with <. The error comes when the heap first compares those two entries. That can be the push, or a later push or pop.
The heapq docs name this problem, and their fix is a count in the middle. Here's how the two comparisons run:
| Field compared | No count | A count in the middle |
|---|---|---|
| 1. the priority | 30 == 30: a tie, go on | 30 == 30: a tie, go on |
| 2. the next field | dict < dict: TypeError | 0 < 1: decided here, and the dicts are never compared |
Counts are never equal, so every tie ends at the count. Counts also go up, so equal priorities come out in the order they went in:
import itertools
jobs = [(2, {"name": "resize"}), (1, {"name": "bill"}), (2, {"name": "email"})]
h, count = [], itertools.count()
for priority, job in jobs:
heapq.heappush(h, (priority, next(count), job))
print([heapq.heappop(h)[2]["name"] for _ in range(3)])
['bill', 'resize', 'email']
itertools.count() hands out 0, 1, 2 and so on. Any number that goes up works just as well, such as an int you add 1 to.
In the editor, run_order(jobs) takes jobs as dicts with a "name" and a "priority", and its last line pops them all. Write the one push inside the loop, with the count in the middle.