24/42
Part 6 of 8 · The best setLearn and do

combinations visits every set once, and one tuple key ranks them

With only a handful of machines, you can try every set, and Python's itertools lists the sets for you.

from itertools import combinations

names = sorted(MACHINES)
every = [group for size in range(1, len(names) + 1)
         for group in combinations(names, size)]
fits = [group for group in every if gpus(group) >= 8]
print(len(every), len(fits))
for group in every[4:9]:
    print(group)
63 53
('ember',)
('fjord',)
('atlas', 'birch')
('atlas', 'cedar')
('atlas', 'delta')

itertools.combinations(names, size) hands out every set of size names. A loop over sizes from 1 up visits every set once, the small ones first.

Sort the names first and you get two orders for free. Each group lists its names alphabetically, and the groups of one size come out in alphabetical order too. The itertools docs promise both when the input is sorted.

n machines have 2n−12^n - 1 sets that aren't empty: each machine is in or out, which makes 2 to the power n choices, and one of them is the empty set. That's 63 here, and 53 of them have at least 8 GPUs.

To rank the sets, write the order as a tuple. Fewest machines first, then the most GPUs, then the names alphabetically, is the key (len(group), -gpus(group), group). Python compares tuples field by field, and the first field that differs decides.

Predict

Two sets of 2 machines: birch and fjord with 10 GPUs, birch and cedar with 8. Under the key (len, -gpus, names), which sorts first?

Pick an answer above to see the rest