13/30
Part 4 of 7 · Why not a heapLearn and do

A heap pops the best key in O(log n)

A heap is the usual tool for "always take the best", and it's where many people start. One candidate who reported the movie playlist tried a heap first and got stuck on it for a long time, then switched to sorted lists. Another's advice was to skip the heap (2 reports). It helps to see where it works and where it stops.

For level 1 alone, a heap is fine. heapq.heapify turns the list of keys into a heap in O(n). Each heappop returns the smallest key in O(log n), so a loop pops the keys in billboard order:

import heapq

heap = [(-score, title) for title, score in CATALOG.items()]
heapq.heapify(heap)
print(heap[0])
print(heap)
(-9, 'Comet')
[(-9, 'Comet'), (-7, 'Harbor'), (-5, 'Orbit'), (-3, 'Tundra'), (-7, 'Maple')]

Only heap[0] has a known place. The rest of the list isn't sorted: Maple sits last even though it's the third best. So you never read a heap's list in order. You pop it.

To start the next loop, keep the popped keys and heapify them again, or keep a second heap for the shown titles. Either is O(n) per loop or O(log n) per call.

The editor holds one_loop. Write one_loop(scores): heapify a key per title, then pop every key and return the titles in the order they came out.