Embercode
✕
Greedy AlgorithmsQuick quiz

Balloons and intervals in Python

8 questions. Covers Merge intervals and insert an interval in Python.

Questions 1 to 5 of 8

  1. 1. What does this code print? ``python from dataclasses import dataclass @dataclass(frozen=True) class Balloon: start: int end: int def min_arrows(balloons): if not balloons: return 0 ordered = sorted(balloons, key=lambda b: b.end) arrows = 1 arrow_at = ordered[0].end for b in ordered[1:]: if b.start >= arrow_at: arrows += 1 arrow_at = b.end return arrows pair = [Balloon(1, 4), Balloon(4, 5)] print(min_arrows(pair)) ``
  2. 2. Why does the balloon method sort the balloons by their end number?
  3. 3. What does this code print? ``python from dataclasses import dataclass @dataclass(frozen=True) class Interval: start: int end: int def merge(intervals): ordered = sorted(intervals, key=lambda item: item.start) merged = [] for nxt in ordered: if merged and nxt.start <= merged[-1].end: last = merged[-1] merged[-1] = Interval(last.start, nxt.end) else: merged.append(nxt) return merged print(merge([Interval(1, 6), Interval(2, 4), Interval(5, 9)])) ``
  4. 4. Put the steps of the balloon method in order.

    Use the arrows to put the steps in order.

    1. 1.Shoot the first arrow at the end of the first balloon
    2. 2.For each later balloon, if its start is after the arrow, shoot a new arrow at its end
    3. 3.Return the number of arrows
    4. 4.Sort the balloons by end
  5. 5. In merge intervals, why does the current group's end become max(last.end, nxt.end)?

4 question(s) left on this page.