Predict the output
What does this print?
import heapq
rules = [[2, 0], [2, 1], [0, 3]]
after: dict[int, list[int]] = {i: [] for i in range(4)}
waiting = [0] * 4
for a, b in rules:
after[a].append(b)
waiting[b] += 1
ready = [t for t in range(4) if waiting[t] == 0]
heapq.heapify(ready)
order = []
while ready:
t = heapq.heappop(ready)
order.append(t)
for nxt in after[t]:
waiting[nxt] -= 1
if waiting[nxt] == 0:
heapq.heappush(ready, nxt)
print(order)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [2, 0, 1, 3]
Right: only 2 is free at first; then 0 is smaller than 1, and 0 frees 3.
At every step the heap hands back the smallest ready task, which builds the smallest valid order.
Why not the others?
- B [0, 1, 2, 3]. 0 and 1 both wait for 2.
- C [2, 0, 3, 1]. After 0, both 1 and 3 are ready, and 1 is smaller.