Code RoomHeap compares tuples not items
MediumPrep Room Coding #1908

Heap compares tuples not items

Code reviewCode quality & reviewMid–Senior~16 min

Review this Python code that keeps the top-N items by score using a heap.

What a strong answer looks like

Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.

0:00 of about 16 min
Mark a line and say what kind of problem it is.0 findings
1import heapq
2 
3class Item:
4 def __init__(self, score, payload):
5 self.score = score
6 self.payload = payload
7 
8def top_n(items, n):
9 heap = []
10 for it in items:
11 heapq.heappush(heap, (it.score, it))
12 if len(heap) > n:
13 heapq.heappop(heap)
14 return [pair[1] for pair in heap]
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.