30/42
Part 7 of 8 · The worked exampleLearn and do

On these shifts, trying every set finds 3, and two greedy rules find more

Now run the search that tries every set against two greedy rules, on the same nine shifts.

from itertools import combinations

SHIFTS = [(1, 3), (1, 5), (2, 8), (4, 6), (6, 12), (7, 10), (9, 14), (11, 14), (13, 14)]


def fewest_by_trying(shifts, start, end):
    days = set(range(start, end + 1))
    for size in range(1, len(shifts) + 1):
        for group in combinations(shifts, size):
            if days <= {d for s, e in group for d in range(s, e + 1)}:
                return size
    return -1


print(fewest_by_trying(SHIFTS, 1, 14))
3

The obvious answer tries every set of shifts, smallest first, and returns the size of the first set that covers. That's O(2^n) sets, each checked in O(n L) for a range of L days. It finds 3.

Then come the greedy rules people reach for. They're worth naming, because both fail here:

  • Longest shift first, skipping any that adds no new day: (2, 8), then (6, 12), then (9, 14), then (1, 5) for day 1. That's 4.
  • In start order, take each shift that extends what's covered: (1, 3), (1, 5), (2, 8), (6, 12), (9, 14). That's 5.

In the editor, write the loop of take_what_extends(shifts, start, end): the second rule, which takes each shift in start order that reaches past covered. On SHIFTS it takes 5.