Embercode
✕
HeapsQuick quiz

Ugly numbers and comparators

8 questions. Covers Custom comparators and tie-breaking in heapq.

Questions 1 to 5 of 8

  1. 1. What does this print? ``python import heapq class NoOrder: def __init__(self, name): self.name = name heap = [] heapq.heappush(heap, NoOrder("A")) print("first push ok") try: heapq.heappush(heap, NoOrder("B")) except TypeError as e: print("TypeError:", e) ``
  2. 2. Each job is pushed as a tuple (priority, arrival, name). What does this print? The names are joined by single spaces. ``python import heapq pq = [] for name, priority, arrival in [("X", 3, 7), ("Y", 1, 9), ("Z", 3, 2), ("W", 1, 4)]: heapq.heappush(pq, (priority, arrival, name)) out = [] while pq: out.append(heapq.heappop(pq)[2]) print(" ".join(out)) ``
  3. 3. A comparison function is meant to order jobs by priority. Two jobs both have priority 2. Which problem does it cause? ``python def bad(a, b): return -1 if a.priority <= b.priority else 1 ``
  4. 4. The function below should give the ugly numbers 1, 2, 3, 4, 5, 6, 8, 9, 10, 12. Its output for n = 10 has 6 twice. Which part is the cause? ``python def ugly_numbers(n): ugly = [0] * n ugly[0] = 1 i2 = i3 = i5 = 0 for k in range(1, n): next2 = ugly[i2] * 2 next3 = ugly[i3] * 3 next5 = ugly[i5] * 5 nxt = min(next2, next3, next5) ugly[k] = nxt if nxt == next2: i2 += 1 elif nxt == next3: i3 += 1 elif nxt == next5: i5 += 1 return ugly ``
  5. 5. What is the 11th ugly number?

5 question(s) left on this page.