Counting Principles
Probability Theory
Count Without Listing Every Outcome
Counting principles give you formulas for the number of ways events can occur — without actually listing them all. They are the foundation of probability calculations.
- Multiplication principle — Multiply choices across independent stages
- Permutations — Order matters; arrange r items from n distinct items
- Combinations — Order does not matter; choose r items from n
- Binomial coefficient — The number of ways to choose r successes from n trials
What You'll Learn
- 1Apply the multiplication principle to multi-stage designs and state when stages are genuinely independent
- 2Distinguish permutation from combination problems by testing whether reordering changes the outcome
- 3Handle repeated letters, identical objects, and stars-and-bars distributions
- 4Convert counting results into exact probabilities for poker hands and grid searches
Probability is counting with a denominator. Before you can write you must be able to compute and without drawing a Venn diagram the size of a parking lot. Combinatorics provides the closed forms: products for staged choices, factorials for full orderings, binomial coefficients for unordered selections. The formulas are short, but the real work is diagnostic — deciding which formula a word problem actually demands, because choosing permutations when the problem wants combinations inflates the count by a factor of and every downstream probability inherits the error.
The Multiplication Principle, Precisely
If a task decomposes into stages where stage offers options regardless of how earlier stages were resolved, the total number of complete designs is the product . A regional license plate reads two letters followed by three digits: 26 choices for each letter and 10 for each digit give plates. Forbidding repetition changes the later stages rather than the principle: after the first letter only 25 remain, after the first digit only 9, yielding . The qualifier "regardless of earlier choices" is the load-bearing clause. If stage two's options depend on stage one's selection — as with drawing cards without replacement — you still multiply, but each factor becomes a conditional count, which is exactly the multiplication rule of probability in disguise.
# License plates: two letters then three digits
letters, digits = 26, 10
with_repetition = letters ** 2 * digits ** 3
without_repetition = letters * (letters - 1) * digits * (digits - 1) * (digits - 2)
print(f"With repetition: 26 x 26 x 10 x 10 x 10 = {with_repetition:,}")
print(f"Without repetition: 26 x 25 x 10 x 9 x 8 = {without_repetition:,}")
# Outfits across independent clothing stages
outfits = 3 * 4 * 2
print(f"\n3 shirts x 4 pants x 2 shoes = {outfits} outfits")
Factorials: Counting Full Arrangements
The factorial counts the orderings of distinct objects: the first position can be any of , the second any of the remaining , and the cascade multiplies out. Ten distinct books can be shelved in ways — a number large enough that listing them is hopeless and small enough that you can still verify it in Python. The convention is not a trick: there is exactly one way to arrange nothing, and that single arrangement keeps every permutation and combination formula consistent at the boundary . Factorials grow faster than exponentials of modest bases, so and friends are always computed through cancellation or logs, never by expanding 52! outright.
import math
from itertools import permutations, combinations
for n in range(1, 11):
print(f"{n:2d}! = {math.factorial(n):>13,}")
print(f"0! = {math.factorial(0)} (one empty arrangement)")
Permutations When Order Matters
A permutation is an ordered selection. Choosing positions out of distinct objects gives , which you can read as "first pick orderings, then throw away the tail arrangements of the unchosen objects." Five books, three shelves: ordered triples. The diagnostic question is simple — does swapping two chosen items create a new outcome? Podium finishes, password character sequences, and shortlist rankings all say yes, so they take permutations. Note that a permutation is also a combination times : the 60 ordered triples equal 10 unordered trios times 6 arrangements each. Keeping that bridge in view prevents most formula-confusion errors.
n, r = 5, 3
print(f"P({n}, {r}) = {n}!/({n}-{r})! = {math.perm(n, r)}")
books = ['A', 'B', 'C', 'D', 'E']
listed = list(permutations(books, 3))
print(f"itertools.permutations yields {len(listed)} ordered triples")
print("First five:", listed[:5])
Combinations When Order Does Not
When the selection is a committee, a pizza topping set, or a hand of cards, internal order carries no information — and every permutation you counted was copies of the same pick. Dividing fixes it, producing the binomial coefficient:
Five books choose three: distinct trios. Ten people form a three-person committee: . The symmetry often shortens arithmetic — choosing three to include is choosing seven to exclude — and Pascal's rule explains why the coefficients build the familiar triangle. In probability, the binomial coefficient is the engine of every "exactly successes" count: there are ways to choose which trials succeeded, each with probability .
| Task | Order matters? | Count | Value for n = 5, r = 3 |
|---|---|---|---|
| Podium from 5 runners | Yes | 60 | |
| Committee from 5 people | No | 10 | |
| Password of 3 distinct digits | Yes | 720 | |
| 3-topping pizza from 10 options | No | 120 | |
| Full arrangement of 5 books | Yes | 120 |
n, r = 5, 3
print(f"C({n}, {r}) = {n}!/({r}!({n}-{r})!) = {math.comb(n, r)}")
listed_combos = list(combinations(books, 3))
print(f"itertools.combinations yields {len(listed_combos)} unordered trios")
print("Each trio appears in 3! = 6 orders among the 60 permutations.")
assert math.perm(n, r) == math.comb(n, r) * math.factorial(r)
print("Bridge verified: P(n, r) = C(n, r) x r!")
Repetitions, Multisets, and Stars and Bars
Two refinements handle the messy cases. Distinct objects with repeated types — the eleven letters of MISSISSIPPI, with four I's, four S's, two P's, and one each of M and A — are counted by dividing out the internal rearrangements of identical items: distinct arrangements. Identical objects distributed into distinct bins is the stars-and-bars problem: giving 10 identical candies to 3 children allows repeats and empty hands, and the count is . The bars separate bins and the stars are the candies; every placement of two bars among twelve slots is one distinct allocation. If each child must receive at least one candy, pre-place one candy each and apply stars and bars to the remaining seven, giving .
from collections import Counter
word = 'MISSISSIPPI'
counts = Counter(word)
denominator = math.prod(math.factorial(v) for v in counts.values())
arrangements = math.factorial(len(word)) // denominator
print(f"{word}: letter counts {dict(counts)}")
print(f"Distinct arrangements = 11!/(4!4!2!) = {arrangements:,}")
def stars_and_bars(n_objects, n_bins):
return math.comb(n_objects + n_bins - 1, n_bins - 1)
print(f"\n10 identical candies to 3 children: C(12, 2) = {stars_and_bars(10, 3)}")
print(f"At least one each (pre-allocate 3): C(9, 2) = {stars_and_bars(7, 3)}")
Counting Your Way to Poker Probabilities
The formulas become probability the moment you divide by the sample space. A five-card poker hand is any selection. A full house — three of one rank and two of another — is built in stages: pick the tripled rank (13 ways), pick its suits , pick the paired rank from the remaining 12, pick its suits . The multiplication principle gives full houses, so the probability is , roughly one in 694 hands. The same staged counting prices hyperparameter grid searches — 5 learning rates times 4 depths times 3 widths is 60 configurations — and sizes permutation tests, where of the label arrangements are unique splits for a two-group comparison of size .
total_hands = math.comb(52, 5)
full_houses = math.comb(13, 1) * math.comb(4, 3) * math.comb(12, 1) * math.comb(4, 2)
royal_flushes = 4 # one per suit
print(f"Five-card hands: C(52, 5) = {total_hands:,}")
print(f"Full houses: 13 x C(4,3) x 12 x C(4,2) = {full_houses:,}")
print(f"P(full house) = {full_houses / total_hands:.6f} (~1 in {total_hands // full_houses})")
print(f"P(royal flush) = {royal_flushes / total_hands:.8f}")
# Grid search sizing for a model sweep
grid = 5 * 4 * 3
print(f"\nGrid search: 5 lrs x 4 depths x 3 widths = {grid} fits")
💡When counts explode, switch to logs
scipy.special.gammaln, or SciPy's comb(..., exact=True), and never expand full factorials in production code.Common Mistakes
Using permutations for a committee or team selection
Fix: Ask whether swapping two members creates a new entity; if not, divide by r! and use combinations.
Forgetting to divide by factorials of repeated types
Fix: Any multiset with identical elements needs the correction 1 / (n1! n2! ...), as in MISSISSIPPI's 34,650 arrangements.
Applying the multiplication principle when stages are constrained
Fix: If later options shrink because of earlier picks, use conditional counts — the probability multiplication rule — rather than fixed stage sizes.
Best Practices
- Write the stage structure of a counting problem before selecting a formula
- Verify small cases by exhaustive enumeration with itertools, then trust the closed form
- Use math.comb and math.perm for exact integers; reserve logs for coefficients that overflow
- Divide counting results by the sample space size only after confirming every outcome is equally likely
Key Takeaways
- The multiplication principle multiplies stage counts; it stays valid under dependence as long as factors become conditional
- Permutations count ordered selections, combinations count unordered ones, and P(n, r) = C(n, r) times r!
- Repeated types divide by internal factorials; stars and bars handles identical objects in distinct bins
- Poker probabilities are staged counts over C(52, 5): full houses are 3,744 hands out of 2,598,960
Frequently Asked Questions
How do I decide between permutations and combinations?
Run the swap test: if exchanging two selected items produces a different outcome (podium places, PIN digits), count permutations. If the exchange produces the same outcome (committee membership, hand of cards), count combinations. When in doubt, count permutations and divide by — it is always safe.
Why is zero factorial defined as one?
Because there is exactly one arrangement of the empty set, and because every formula that cancels factorials — , — requires to stay consistent. Defining it otherwise breaks the binomial theorem's boundary terms.
Can I compute binomial coefficients without factorials?
Yes, and you should for large inputs. Pascal's recurrence builds each value from two smaller ones with integer arithmetic only, while scipy.special.gammaln handles the logarithmic form for coefficients beyond machine integer range.
Interview Questions
Q1: How many 5-letter passwords use distinct letters from the 26-letter alphabet?
P(26, 5) = 26 × 25 × 24 × 23 × 22 = 7,893,600. Order matters and repetition is banned, so it is a permutation, not 26 to the power 5.
Q2: Explain why C(n, r) = P(n, r) / r!.
Each unordered selection of r items corresponds to exactly r! orderings of those items. Counting permutations counts every selection r! times, so dividing by r! recovers the combination count.
Q3: What is the probability of a full house in five-card poker?
Choose the tripled rank (13), its suits C(4,3) = 4, the paired rank (12), and its suits C(4,2) = 6, giving 3,744 hands. Divide by C(52, 5) = 2,598,960 to get about 0.00144, roughly one in 694.