18/28
Part 4 of 6 · Rows and columnsLearn and do

Greedy by rank can leave a slot empty

Greedy fills each slot with the best title that fits it, never looking ahead. Under the screen rule that's safe. Under the grid rule it can fail. Here column 1 already holds B:

def greedy(row, width, columns):
    head = []
    for j in range(width):
        pick = next((t for t in row if t not in head and t not in columns[j]), None)
        if pick is None:
            break
        head.append(pick)
    return head


print(greedy(["A", "B"], 2, [set(), {"B"}]))
['A']

Greedy puts A in slot 0, because A is the row's best title. Then slot 1 needs a title other than A and B, and the row has none. But B, A fills both slots: B is free in column 0, and A is free in column 1.

So there is a real choice, and it's a product choice before it's an algorithm:

  • Rank first. Each slot gets the best title that fits, as the problem says. Sometimes a slot stays empty.
  • Fill first. Fill the most slots, even if it moves a lower-ranked title ahead of a better one.

The practice problem asks for rank first, and you should say that you noticed the other option. To know what rank first costs, compute the best count. With a handful of titles, trying every order is fine: 8 titles in 2 slots is 56 orders.

In the editor, greedy_count is given. Write best_count(row, width, columns): the most slots, from slot 0 with no gap, that any order of different titles can fill. Use itertools.permutations.