Code

The Quest Heap

A heap always keeps its smallest item at the front, ready to grab, without fully sorting everything. Python's heapq module turns an ordinary list into a min-heap:

import heapq

h = []
heapq.heappush(h, 7)
heapq.heappush(h, 2)
heapq.heappush(h, 5)
print(h[0])               # 2  (peek)
print(heapq.heappop(h))   # 2
print(heapq.heappop(h))   # 5

Push and pop are O(log n), peeking is O(1). heapq.heapify(list) turns an existing list into a heap in O(n).

Priority queues

Push tuples and the heap compares the first item, then the next to break ties: (priority, name). Low number = most urgent.

Top-k

heapq.nlargest(k, items) and heapq.nsmallest(k, items) find the best few without sorting the whole list, great for leaderboards.

Pip tip: heapq only does min-heaps. For a max-heap, push negated numbers: heappush(h, -score).

Assignment

  1. top_k(scores, k) returns the k highest scores, highest first. Don't change the scores list.
  2. quest_order(quests) takes (priority, name) tuples and returns the names in the order a heap pops them (lowest priority number first, ties by name). Use heappush/heappop, and don't change the quests list.