Embercode
✕
HeapsQuick quiz

Heap bug hunt

8 questions. Covers Debugging lab: heap bugs in Python.

Questions 1 to 5 of 8

  1. 1. This heap should be a min-heap. Adding 5, 1, 9 and 3, then polling, prints 9 5 3 1 instead of 1 3 5 9. Which line causes it? ``python def before(self, x, y): return x > y def add(self, x): self.a[self.size] = x i = self.size self.size += 1 while i > 0: p = (i - 1) // 2 if not self.before(self.a[i], self.a[p]): break self.swap(i, p) i = p ``
  2. 2. The add method in this heap is correct. Adding 5, 1, 9, 3, 7, 2 and 8 in that order, then polling until the heap is empty, prints 1 2 7 8 5 9 3, which is out of order. Which line in poll causes it? ``python def poll(self): top = self.a[0] self.size -= 1 self.a[0] = self.a[self.size] i = 0 while True: l = 2 * i r = 2 * i + 2 best = i if l < self.size and self.before(self.a[l], self.a[best]): best = l if r < self.size and self.before(self.a[r], self.a[best]): best = r if best == i: break self.swap(i, best) i = best return top ``
  3. 3. The code prints b(3), but a should come first now. What is the bug? Task compares by its priority field in __lt__. ``python import heapq class Task: def __init__(self, priority, name): self.priority = priority self.name = name def __lt__(self, other): return self.priority < other.priority def __repr__(self): return f"{self.name}({self.priority})" heap = [] a = Task(5, "a") b = Task(3, "b") c = Task(8, "c") heapq.heappush(heap, a) heapq.heappush(heap, b) heapq.heappush(heap, c) a.priority = 1 print("peek:", heap[0]) # prints b(3) ``
  4. 4. Adding 17 values to this heap raises IndexError: list assignment index out of range. What is missing? ``python class Heap: def __init__(self): self.a = [None] * 16 self.size = 0 def add(self, x): self.a[self.size] = x i = self.size self.size += 1 while i > 0: p = (i - 1) // 2 if self.a[i] >= self.a[p]: break self.a[i], self.a[p] = self.a[p], self.a[i] i = p ``
  5. 5. What does this print? ``python def is_min_heap(a, size): for i in range(1, size): if a[(i - 1) // 2] > a[i]: return False return True print(is_min_heap([7, 3, 8, 5, 9], 5)) ``

5 question(s) left on this page.