
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:
heapqonly does min-heaps. For a max-heap, push negated numbers:heappush(h, -score).
Assignment
top_k(scores, k)returns thekhighest scores, highest first. Don't change thescoreslist.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). Useheappush/heappop, and don't change thequestslist.
top_k(scores, k)returns thekhighest scores, highest first. Don't change thescoreslist.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). Useheappush/heappop, and don't change thequestslist.
main.py Python sleeping
Press Run to try your code, then Check to test it.