27/40
Part 6 of 8 · Lazy deletesLearn and do
To change a key, push a new entry or index the heap, never write it in place
Sometimes an entry's key changes after it is in the heap, such as a credit whose expiry moves earlier. Changing it in place looks harmless.
h = [[10, "trial"], [30, "promo"], [45, "refund"], [60, "bonus"]]
heapq.heapify(h)
h[3][0] = 5
print([heapq.heappop(h)[1] for _ in range(4)])
bonus sat at the bottom, due at 60. You write its expiry as 5 in place, and pop all four. Which comes out first?
Pick one to see what it prints.
Pick an answer above to see the rest