Embercode
✕
Greedy AlgorithmsQuick quiz

Greedy bug hunt in Python

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

Questions 1 to 5 of 8

  1. 1. This function should return the largest number of meetings that do not clash. ``python def greedy(meetings): ordered = sorted(meetings, key=lambda m: m.start) count = 0 last_end = float('-inf') for m in ordered: if m.start >= last_end: count += 1 last_end = m.end return count `` For the meetings [1, 10], [2, 3] and [4, 5] it returns 1, but the answer is 2. What is the bug?
  2. 2. The correct function sorts meetings by end time. Meetings [3, 9] and [5, 9] both end at 9. Which statement is true?
  3. 3. What does this Python code print? ``python from dataclasses import dataclass @dataclass(frozen=True) class Meeting: start: int end: int meetings = [Meeting(1, 3), Meeting(3, 4), Meeting(2, 5)] ordered = sorted(meetings, key=lambda m: m.end - m.start) count = 0 last_end = float('-inf') for m in ordered: if m.start >= last_end: count += 1 last_end = m.end print(count) ``
  4. 4. This line is in an otherwise correct greedy function on meetings. What is the bug? ``python ordered = sorted(meetings, key=lambda m: m.end - m.start) ``
  5. 5. This loop should take as many meetings as possible. Meetings that touch are allowed. ``python def pick(sorted_meetings): count = 0 last_end = float('-inf') for m in sorted_meetings: if m.start > last_end: count += 1 last_end = m.end return count `` The meetings [1, 3], [3, 5] and [5, 7] all touch, so the answer is 3. This function returns 2. What is the bug?

5 question(s) left on this page.