Python 3D Academyবাংলা

Subsets and combinations: choosing toppings

🌍 In real life. A pizza stall at the school fair offers three toppings: cheese, olive and corn. You may have any of them, all of them, or none. How many different pizzas can you order? Go through the toppings one by one and decide, for each: take it or skip it. Cheese: yes or no. Olive: yes or no. Corn: yes or no. Every way of answering those three questions is one pizza.

And if the stall says "choose exactly 2 of your 4 favourite toppings", you only want the groups of 2, and cheese-with-olive is the same pizza as olive-with-cheese. Both questions are backtracking with a different rule for what counts as an answer.

The idea in one sentence: to list every subset, decide take-or-skip for each item in turn; to list every combination of k items, choose items only to the right of the last one chosen, and stop when you have k.

Its words:

  • subset: any selection of the items, from none to all; order doesn't matter
  • combination: a subset of exactly k items
  • decision tree: the tree of every choice; each path from the top to a bottom is one finished set of choices: an answer, or a dead end
  • start index: in combinations, the first item you may still choose; it stops the same group being made twice in another order

Subsets, step by step:

  1. at item i: if there are no items left, the path is a subset: collect a copy
  2. choose: take items[i], then explore item i + 1
  3. undo: put it back, then explore item i + 1 without it

The tree for three toppings has 8 bottoms, one per pizza (+ is take, − is skip):

Combinations, step by step:

  1. if the path has k items, collect a copy
  2. otherwise, for every item from start to the end: choose it, explore with start = i + 1, undo
  3. a path that runs out of items before reaching k is a dead end

Choosing 2 of 4 toppings. Taking only items to the right makes egg-ham, but never ham-egg:

Why it is correct. For subsets: two subsets are different exactly when some item is in one and not the other, and the tree splits on every item once, so each subset is reached by exactly one path: none is missed, none is repeated. For combinations: every group of k can be written in the items' order, and the start index only ever lets you go right, so each group is built exactly once, in that order. The undo makes sure each branch starts from the path its parent had.

What it costs, by counting. Each item doubles the number of subsets: 3 toppings give 2 × 2 × 2 = 8, and n items give 2ⁿ. Copying each into the answer takes up to n steps, so listing them all is O(n × 2ⁿ):

  • 10 items: 1,024 subsets
  • 20 items: 1,048,576

There is no way round this: the answer itself is that big. Combinations are fewer: choosing k of n gives n! / (k! (n − k)!), "n choose k"; 2 of 4 is 6, and 2 of 5 is 10. Python's itertools.combinations lists them in the same order.

def subsets(items):
    out, path = [], []
    def go(i):
        if i == len(items):
            out.append(path[:])        # a copy: path keeps changing
            return
        path.append(items[i])          # choose: take it
        go(i + 1)                      # explore
        path.pop()                     # undo
        go(i + 1)                      # explore without it
    go(0)
    return out

def combinations(items, k):
    out, path = [], []
    def go(start):
        if len(path) == k:
            out.append(path[:])
            return
        for i in range(start, len(items)):
            path.append(items[i])      # choose
            go(i + 1)                  # explore: only items to its right
            path.pop()                 # undo
    go(0)
    return out

from itertools import combinations as library_combinations

print(subsets(["cheese", "olive", "corn"]))
print(combinations(["egg", "ham", "corn", "olive"], 2))
print(list(library_combinations(["egg", "ham", "corn", "olive"], 2)))

Mistakes and edge cases.

  • out.append(path) without a copy: every answer is the same list, which ends up empty after the last undo, so you get [[], [], …]; append path[:]
  • go(i) instead of go(i + 1) in combinations: an item can be chosen again, and groups like egg-egg appear
  • starting each loop from 0: the same group appears in every order (egg-ham and ham-egg)
  • empty input: the only subset of [] is [] itself; combinations(items, 0) is [[]]
  • k bigger than the number of items: there are no groups, so the answer is []

Quiz

  1. What does this print?

    def subsets(items):
        out, path = [], []
        def go(i):
            if i == len(items):
                out.append(path[:])        # a copy: path keeps changing
                return
            path.append(items[i])          # choose: take it
            go(i + 1)                      # explore
            path.pop()                     # undo
            go(i + 1)                      # explore without it
        go(0)
        return out
    
    print(subsets(["x", "y"]))
  2. How many subsets do 5 toppings have?

    • 32: each topping doubles the count, 2⁵
    • 25
    • 10
  3. This prints [[], [], [], []] instead of the subsets of ['x', 'y']. Which line is wrong?

    def subsets(items):
        out, path = [], []
        def go(i):
            if i == len(items):
                out.append(path)
                return
            path.append(items[i])
            go(i + 1)
            path.pop()
            go(i + 1)
        go(0)
        return out
  4. In combinations, why does the loop start at start and recurse with i + 1?

    • So each group is made once, in item order, and no item is chosen twice
    • To make it faster but with the same answers as starting at 0
    • Because Python's range can't start at 0
  5. Listing every subset of n items: what is the Big-O?

    • O(n × 2ⁿ): 2ⁿ subsets, each copied in up to n steps
    • O(n²)
    • O(n log n)

Coding tasks

  1. Write subsets(items): return every subset as a list of lists, by deciding take-or-skip for each item in turn, trying take first (so subsets(['x', 'y']) is [['x', 'y'], ['x'], ['y'], []]).

  2. Write combinations(items, k): every group of exactly k items, each as a list in the items' order, listed in the order backtracking finds them (choose only items to the right of the last one chosen).

  3. Each topping has a price in taka. Write pizzas_within(prices, budget): how many different sets of toppings (each topping at most once, including none) cost at most budget in total. Use take-or-skip backtracking, and stop exploring a branch as soon as its cost is over the budget.