progress

~/problems / Counting / Combinatorics / inclusion-exclusion

Tasting panel with every group

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A cheese fair picks a tasting panel of exactly k people. Candidates come in groups (farmers, chefs, ...): groups[g] people in group g, all different people. The panel needs at least one person from every group.

Write panel_count(groups: list[int], k: int) -> int: the exact number of valid panels.

panel_count([2, 1], 2)       # 2      (the lone chef plus either farmer)
panel_count([2, 2], 2)       # 4      (C(4,2) = 6, minus the 2 panels from one group only)
panel_count([3, 1, 1], 2)    # 0      (3 groups can't all fit on a panel of 2)
panel_count([4, 5, 6], 3)    # 120    (one from each: 4 · 5 · 6)

Count the bad panels with inclusion-exclusion: start from C(total, k), subtract panels missing each group, add back those missing two groups, and so on. A panel missing the groups in S is a k-subset of the people outside S.

Up to 10 groups of up to 500 people; 0 <= k <= sum(groups). math.comb is fine.

⭐ Bonus: a speed test with 10 big groups and k = 1000 earns a star with one comb per subset of groups.

Show hint

loop over subsets S as bitmasks and add (-1) ** |S| * comb(total - size(S), k).

Topic: Combinatorics / inclusion-exclusion. Stars and bars, nCr identities, |A u B| = |A| + |B| - |A n B|.

0:00
Ctrl ' run · Ctrl ↵ submit
esc