Counting: rules, binomial coefficients, pigeonhole and inclusion-exclusion
A rigorous review of counting: sum and product rules, bijections, ordered selections, permutations and combinations with and without repetition, stars and bars, the binomial theorem, double counting, pigeonhole and inclusion–exclusion. Each formula is checked against explicit enumeration.
After this lesson you can
- Choose the correct counting model for order, repetition and distinguishability and justify it by a bijection
- Prove binomial identities by double counting as well as algebra
- Apply the pigeonhole principle, including its generalized form, and prove R(3, 3) = 6
- Count derangements and surjections using inclusion–exclusion
- Implement enumerators and check formulas by brute force with exact integers
Before you start
Motivation: count before enumerating
Before writing an exhaustive search, take ten seconds to count: how many cases? The answer determines feasibility or whether another approach is needed.
- Hyperparameter grids. Five hyperparameters with ten values each give configurations. At one minute per training run, that is over two months of compute. This is the product rule, and why random or Bayesian search replaces grids beyond two or three axes.
- Feature selection. With features there are subsets. Evaluating a model per subset is impossible, hence greedy methods and regularization.
- Routes. A traveling salesperson visiting 20 cities and returning to the origin has distinct tours. Even at a billion per second it takes more than a year.
- Token sequences. With GPT-2’s 50,257-token vocabulary and a context of 1024 positions, there are possible sequences. A language model cannot memorize that space: it must generalize.
- Hypotheses. On 6 input bits there are Boolean functions. Counting how many a model family can express is precisely the growth function; its bound, the Sauer–Shelah lemma, is a counting argument like those here.
- Games. Go has about legal positions on a board (Tromp, 2016). AlphaZero therefore does not explore the entire game tree: it samples a tiny part guided by a network.
These figures follow from a handful of principles: add disjoint cases, multiply successive choices, find a bijection with something countable, divide when each object is counted repeatedly, and correct overlapping cases with alternating signs. This lesson densely reviews these principles with full proofs and the habit preventing most mistakes: check every counting formula against explicit enumeration in small cases. Finite sums recur in the hypergeometric distribution, recurrences and generating functions.
Basic rules
Everything rests on four facts about finite sets. Recall means a bijection between and (lesson 3’s cardinality).
Proof
The sum rule for two disjoint sets concatenates bijections and ; for sets use induction on . The sequential product form also follows by induction on : group objects by first choice. There are disjoint groups and, by induction on the remaining choices, each has objects; the sum rule gives . The bijection rule is the definition of cardinality. The quotient rule applies the sum rule to the partition of into disjoint fibers, each of size .
∎The sequential product form has a subtlety: the number of options at each step must be constant, not the set. Arranging people in a line, the second position can hold anyone except the first chosen. The candidate set depends on the prior choice, but its size is always , sufficient for .
A decision tree depicts the product rule: root “nothing chosen yet,” each level a choice, each leaf a complete sequence. If each level- node has children, there are leaves.
Ordering and choosing: four situations
Choosing objects from has four interpretations according to whether selection order matters and whether an object may be selected repeatedly. The figure covers all four; now formalize them.
Proof
Both sequence counts use the product rule: with repetition there are choices at each of selections; without repetition, at choice , regardless of previous choices. For combinations without repetition, map each -permutation to its element set. This is surjective and each size- subset is the image of exactly its orderings, so the quotient rule gives . Combinations with repetition are counted next using stars and bars.
∎The figure tests the quotient rule. Without repetition each class has exactly leaves, because distinct symbols have orderings. With repetition, no: multiset has one ordering, three and six. Fibers have different sizes, the quotient rule does not apply and is not even an integer: and give , versus answer . The figure also shows choosing a canonical representative per class, the increasing sequence ( with repetition, without), and counting only those branches.
Words with repeated letters: multinomial coefficients
How many distinct words rearrange MISSISSIPPI? If all 11 letters were distinguishable (add subscripts ) there would be orderings. Removing subscripts, each word corresponds to exactly subscripted orderings (the M, four I’s, four S’s and two P’s among themselves), so the quotient rule gives
Generally the multinomial coefficient with counts length- words with copies of symbol , or equivalently distributions of distinguishable objects into labeled boxes with objects in box . It also follows by choosing each symbol’s positions successively: , a product telescoping to the same fraction. The binomial is : .
Balls into boxes
Many problems become distributing balls among boxes, i.e. functions from a -element set to an -element set. Stanley’s twelvefold way organizes cases by whether balls and boxes are distinguishable and whether the function is arbitrary, injective or surjective. With distinguishable boxes six cases remain, five already known:
| balls in boxes | arbitrary | injective (at most one per box) | surjective (no empty box) |
|---|---|---|---|
| distinguishable balls | |||
| indistinguishable balls |
The surjection entry for distinguishable balls is proved using inclusion–exclusion at the end. Indistinguishable boxes yield Stirling numbers of the second kind, expressible only as an alternating sum (seen later), and integer partitions without a closed formula; see Stirling and Bell numbers.
Stars and bars
A size- combination with repetition on is determined by each element’s multiplicity: copies of element , with . Thus counting multisets counts nonnegative integer solutions of a linear equation, for which there is a useful bijection.
Proof
Write a solution as a string of stars and bars: stars, a bar, stars, a bar, and so on through stars. For example with is . This bijects solutions with length- strings containing exactly bars: the inverse counts stars between successive bars (and before the first and after the last). Such a string is determined by its bar positions, a size- subset of . The bijection rule gives solutions.
For , substitution bijects with solutions of , , of which there are . Visually reserve a star for each box and distribute the rest; or place the bars in of the gaps between stars, without repeating gaps.
∎Feller popularized the bijection and name stars and bars in his probability book. It completes the missing table entry: a size- multiset on elements solves , giving .
Three variants reduce to the same bijection:
- Lower bounds. with : set and count nonnegative solutions of sum 8, .
- Inequalities. Solutions of with are solutions of with slack variable : .
- Monomials. A degree- monomial in variables, with , solves a stars-and-bars equation: there are . Those of degree number by the previous variant. A degree-3 polynomial feature expander over 100 variables (like scikit-learn’s
PolynomialFeatures(degree=3), constant included) produces columns: monomials grow like for fixed and like for fixed , so kernel methods compute inner products in that space without constructing it.
Upper bounds () do not reduce by substitution. They require inclusion–exclusion, covered at the end.
Binomial theorem and Pascal’s triangle
Proof
Combinatorial proof. Expand distributively without commuting: obtain length- words in and , one per choice of a letter from each factor. After commuting, each word with letters becomes , and there are as many as size- subsets of the factors (positions of ): .
Inductive proof. For both sides are 1. Assuming , multiply by and collect the coefficient of : , or by Pascal’s rule below. At and one term is zero and the other 1, as is .
∎Commutativity matters. For matrices, , and only when can cross terms combine into . The combinatorial proof explains this: count words after commuting. Thus holds for commuting matrices and fails generally otherwise. The same argument gives the multinomial theorem:
with terms, one per stars-and-bars solution. The fact that the binomial formula holds for all and coefficients count subsets is the binomial theorem; substituting values gives identities:
- : . Subsets of all sizes are all subsets.
- , , : . A nonempty set has equally many even- and odd-size subsets (bijection: add or remove a fixed element).
- Differentiate with respect to and evaluate at : .
Proof
Fix element of an -element set. Size- subsets split into those containing (choose the other among ) and those not containing it (choose among ): sum rule. Symmetry is the bijection between subsets of size and , the complement.
∎Placing in row , position , yields Pascal’s triangle, with each number the sum of the two above. Its diagonals, rows and row combinations encode many identities.
Proof
For hockey stick, classify size- subsets of by largest element . With largest , the other elements are chosen from in ways. Sum over and index by . You will prove Vandermonde similarly in exercises.
∎The triangle modulo p: Lucas’s theorem
In the figure’s “modulo ” mode, cells divisible by form nested triangular gaps. This is not a visual coincidence: parity of can be read from bits of and .
Proof
First is divisible by for : prime divides the numerator and no denominator factor. By the binomial theorem, as polynomials modulo , and by induction . Then
Expanding the right product, each term has exponent with . Uniqueness of base- representation makes the only term with exponent that with for every (there is none if some , in which case ). Equating coefficients of proves the theorem.
∎The binary corollary counts odd entries in each row: there are as many with bits contained in those of as subsets of the 1-bit set of , namely if has binary ones. Row 21 has odd entries, and in the figure is even because the bit of weight 2 in is absent from 21. Rows , all ones, are entirely odd; rows have odd entries only at the ends, where each new fractal gap starts.
Double counting
An identity between numeric expressions can be proved algebraically, but a technique also explains why: find a set counted by both expressions.
Double counting is also the finite form of Fubini’s theorem (exchanging double-sum order), behind nontrivial proofs such as Pitman’s proof of Cayley’s labeled-tree formula and the Kővári–Sós–Turán extremal-graph bound. When an identity has binomial coefficients, seek the set before induction.
The pigeonhole principle
Proof
The first is the case of the second. For the second, suppose otherwise: if every fiber had at most elements, since fibers partition , we would have , because . Contradiction.
∎The pigeonhole principle is the contrapositive of an obvious claim about injective functions, but its strength lies in choosing pigeons and holes well. It is a nonconstructive existence argument: it guarantees a collision without locating it.
- No universal compressor. No lossless compression algorithm shortens every -bit string: there are length- strings and only shorter strings (including empty). If it compresses one, it lengthens another. This is the combinatorial version of the source coding theorem limits.
- Every hash has collisions. A 256-bit hash applied to distinct inputs gives two equal outputs. Cryptographic hash security does not mean collisions do not exist, but that finding them is infeasible. The birthday paradox, seen in probability, says roughly trials suffice to expect one, not : hash lengths use twice the bits of desired security.
- Divisible sums. Among any integers is a nonempty consecutive block whose sum is divisible by . Pigeons are partial sums ; holes are remainders modulo . Two coincide, with , so divides .
Proof
Let be the sequence. Assign each position the pair : the lengths of the longest increasing subsequence ending at and the longest decreasing subsequence ending at . Suppose both lengths are always . Then there are at most possible pairs and positions: by pigeonhole, two positions have the same pair. But if , appending to the longest increasing subsequence ending at gives ; if , similarly . Either way pairs differ. Contradiction.
∎The bound is tight: has elements and no monotone subsequence of length 4. The proof does not search for the subsequence; labels can however be calculated by dynamic programming that does find it.
First encounter with Ramsey: R(3, 3) = 6
In any six-person group, three mutually know one another or three are mutual strangers. Graphically, color each edge of complete graph red or blue; a triangle with all edges one color always exists.
Proof
Take a vertex of . It has 5 edges and 2 colors, so generalized pigeonhole gives at least of one color, say red, to vertices . If any of , , is red, it forms a red triangle with . Otherwise all three are blue and is blue.
For , arrange vertices in a pentagon, coloring sides red and diagonals blue. Each color forms a 5-cycle, which has no triangles.
∎The central vertex is the entire argument: at least 3 of its 5 edges share a color, and any 3 pentagon vertices have at least one pentagon side (red) and one diagonal (blue), because a 5-cycle has neither 3 pairwise nonadjacent vertices (giving the side) nor 3 pairwise adjacent vertices (giving the diagonal). If the center’s 3 edges are red, the side closes a red triangle; if blue, the diagonal closes a blue one. Enumerating the colorings below confirms more: every coloring has at least two monochromatic triangles (Goodman, 1959), and has exactly 12 colorings without them, the 12 Hamiltonian cycles of (each with its complement).
Ramsey number is the smallest such that every red-blue coloring of contains a red or blue . You proved . It is known , while is known only to lie between 43 and 46 (upper bound Angeltveit and McKay, 2024). Ramsey numbers return with more tools, and Erdős’s exponential lower bound for is a founding example of the probabilistic method: a counting argument proving a good coloring exists without constructing it.
Inclusion–exclusion
The sum rule requires disjoint sets. If they overlap, counts twice, and . For three sets subtract all three pairwise overlaps and add the triple intersection back, having subtracted it once too often. The general pattern alternates signs.
Proof
Check each ‘s contribution to the second formula’s right side (the first follows by subtracting from ). Let and . Element is in exactly when , so contributes
by the binomial theorem. Thus the right side counts exactly elements in no .
∎The inclusion–exclusion principle usually appears in symmetric form: if depends only on , say , the intersections of size contribute equally and
The recipe is always: define “bad properties” , count what happens imposing simultaneously, and alternate signs. Three classic examples follow.
Derangements
A derangement of is a permutation with no fixed points: for all . The hat problem: people leave hats at a cloakroom and receive them back randomly; how many ways give nobody their own?
Let be permutations fixing . Imposing specific fixed points leaves elements to permute freely: . By symmetric inclusion–exclusion,
This is the truncated Taylor series for . The fraction of permutations without fixed points approaches rapidly: alternating-series error is bounded by the first omitted term, so for , and is the nearest integer to . First values are (for ).
There is also for , with a short combinatorial proof. In a derangement, goes to some ( choices). If goes to , they swap and the rest is a derangement of elements. Otherwise “merge” with (forbid going to as previously forbidden from itself), giving a derangement of elements. Derangements return as permutations without length-1 cycles in cycle decomposition.
Surjections
How many surjections are there from an -element set to a -element one? Let be functions not taking value . Forbidding specific values leaves functions:
For example : surjections from 4 to 3 choose the pair sharing an image (), then a bijection from 3 blocks to 3 values (). Dividing by gives Stirling numbers of the second kind, , counting partitions into nonempty blocks. The alternating sum contains huge powers that nearly cancel, so only exact integers can calculate it reliably; the coding exercise checks this.
Euler’s φ function
counts integers in coprime to . If primes dividing are , let be multiples of in . Common multiples of primes indexed by are multiples of their product, so and
where the last equality expands the product. For : . Function is central to modular congruence arithmetic.
Upper bounds in stars and bars
How many solutions of have ? Let be nonnegative solutions with . Imposing such bounds subtracts from the total (the stars-and-bars substitution), so while :
Truncating the sum: Bonferroni
Truncating inclusion–exclusion does not give arbitrary values: partial sums alternate upper and lower bounds. With ,
The first is the union bound, the most-used inequality in learning theory (turning a guarantee for one hypothesis into a simultaneous guarantee for a finite family). The rest are Bonferroni inequalities.
Implementation from scratch
First, lazy generators (Python generators) for three of four families (the fourth, sequences with repetition, is a Cartesian product: itertools.product) and stars-and-bars solutions. Their structure proves their formulas: combinations follow Pascal’s rule (with or without the first element) and -permutations the product rule. Then compare against formulas and itertools.
from math import comb, perm, factorial
import itertools
def k_permutaciones(items, k):
"""Secuencias de k elementos distintos, en orden lexicográfico."""
if k == 0:
yield ()
return
for i, x in enumerate(items):
resto = items[:i] + items[i + 1:]
for cola in k_permutaciones(resto, k - 1): # regla del producto
yield (x,) + cola
def combinaciones(items, k):
"""Subconjuntos de tamaño k (como tuplas crecientes)."""
if k == 0:
yield ()
return
if len(items) < k:
return
primero, resto = items[0], items[1:]
for cola in combinaciones(resto, k - 1): # las que contienen al primero
yield (primero,) + cola
yield from combinaciones(resto, k) # las que no: regla de Pascal
def multicombinaciones(items, k):
"""Multiconjuntos de tamaño k (tuplas no decrecientes)."""
if k == 0:
yield ()
return
if not items:
return
primero = items[0]
for cola in multicombinaciones(items, k - 1): # usar el primero (otra vez)
yield (primero,) + cola
yield from multicombinaciones(items[1:], k) # no volver a usarlo
def composiciones(n, k):
"""Soluciones de x1 + ... + xk = n con xi >= 0."""
if k == 1:
yield (n,)
return
for x in range(n + 1):
for resto in composiciones(n - x, k - 1):
yield (x,) + resto
def barras(x):
"""Estrellas y barras: posiciones (desde 0) de las barras en la cadena."""
pos, i = [], 0
for xi in x[:-1]:
i += xi
pos.append(i)
i += 1
return tuple(pos)
contar = lambda gen: sum(1 for _ in gen)
multi = lambda n, k: comb(n + k - 1, k) if n + k > 0 else 1 # el multiconjunto vacío de un conjunto vacío
casos = 0
for n in range(0, 8):
items = tuple(range(n))
for k in range(0, n + 2):
assert contar(k_permutaciones(items, k)) == perm(n, k)
assert contar(combinaciones(items, k)) == comb(n, k)
assert contar(multicombinaciones(items, k)) == multi(n, k)
# mismo orden que itertools
assert list(k_permutaciones(items, k)) == list(itertools.permutations(items, k))
assert list(combinaciones(items, k)) == list(itertools.combinations(items, k))
assert list(multicombinaciones(items, k)) == list(itertools.combinations_with_replacement(items, k))
casos += 1
for k in range(1, 6):
sols = list(composiciones(n, k))
assert len(sols) == comb(n + k - 1, k - 1)
# la codificación con barras es una biyección sobre los (k-1)-subconjuntos de n+k-1 posiciones
assert sorted(map(barras, sols)) == list(itertools.combinations(range(n + k - 1), k - 1))
casos += 1
print("casos comprobados:", casos, " todos coinciden con las fórmulas y con itertools")
print("ejemplo, (2, 0, 3, 2) ->", barras((2, 0, 3, 2)), " (cadena ★★||★★★|★★)")
print("MISSISSIPPI:", factorial(11) // (factorial(4) ** 2 * factorial(2)),
" palabras distintas por fuerza bruta:", len(set(itertools.permutations("MISSISP"))),
"de", factorial(7), "ordenaciones de MISSISP")The final line checks the quotient rule with shorter MISSISP (one M, two I’s, three S’s, one P), making brute force instant: its orderings yield distinct words, each repeated times.
Now derangements three ways: inclusion–exclusion with exact integers, recurrence, and brute force. Finally the mathematically correct “nearest integer to ” formula evaluated in floating point.
from math import comb, factorial, e
from itertools import permutations
def desarreglos_ie(n):
return sum((-1) ** j * comb(n, j) * factorial(n - j) for j in range(n + 1))
def desarreglos_rec(n):
if n == 0:
return 1
a, b = 1, 0 # D_0, D_1
for m in range(2, n + 1):
a, b = b, (m - 1) * (a + b)
return b
def desarreglos_fb(n):
return sum(all(p[i] != i for i in range(n)) for p in permutations(range(n)))
print(" n IE recurrencia fuerza bruta D_n / n!")
for n in range(9):
ie, rec, fb = desarreglos_ie(n), desarreglos_rec(n), desarreglos_fb(n)
assert ie == rec == fb
print(f"{n:2d} {ie:6d} {rec:8d} {fb:10d} {ie / factorial(n):.6f}")
print("1/e =", round(1 / e, 6))
assert all(desarreglos_ie(n) == desarreglos_rec(n) for n in range(60))
fallo = next(n for n in range(1, 60) if round(factorial(n) / e) != desarreglos_rec(n))
print(f"\nround(n!/e) en coma flotante falla por primera vez en n = {fallo}:")
print(" float:", round(factorial(fallo) / e), " exacto:", desarreglos_rec(fallo))The table confirms all three and convergence to : at the fraction differs from by , below the first-omitted-term bound . The last line is the warning: “nearest integer to ” is exact over reals, but floating-point operations can have relative error up to , and once exceeds that error can exceed half a unit. This first occurs at , with : rounding is off by 6.
Now pigeonhole and Ramsey by brute force. Each coloring is a bit mask (bit = edge ‘s color) and each triangle its three-edge mask: monochromatic if the coloring has all three bits 0 or all 1. We also check Erdős–Szekeres on random permutations.
from itertools import combinations
from collections import Counter
import random
def triangulos_mono(n):
aristas = list(combinations(range(n), 2))
idx = {a: i for i, a in enumerate(aristas)}
tri = [(1 << idx[(a, b)]) | (1 << idx[(a, c)]) | (1 << idx[(b, c)])
for a, b, c in combinations(range(n), 3)]
return [sum(1 for t in tri if m & t == 0 or m & t == t) for m in range(1 << len(aristas))]
for n in (5, 6):
c = triangulos_mono(n)
print(f"K{n}: {len(c)} coloraciones, sin triángulo monocromático: {c.count(0)}, "
f"mínimo de triángulos: {min(c)}")
print("K6, coloraciones por número de triángulos monocromáticos:", sorted(Counter(c).items()))
def mas_larga(a, creciente=True):
"""Longitud de la subsecuencia monótona más larga, por programación dinámica O(N^2)."""
L = [1] * len(a)
for j in range(len(a)):
for i in range(j):
if (a[i] < a[j]) == creciente:
L[j] = max(L[j], L[i] + 1)
return max(L)
rng = random.Random(0)
n = 4
peor = min(max(mas_larga(p), mas_larga(p, False))
for p in (rng.sample(range(100), n * n + 1) for _ in range(500)))
print(f"\n500 secuencias de {n*n+1} números: la monótona más larga mide al menos {peor} (teorema: {n+1})")
extremal = [x for b in range(n) for x in range(n * (b + 1), n * b, -1)]
print("secuencia extremal de", n * n, "elementos:", extremal,
" monótona más larga:", max(mas_larga(extremal), mas_larga(extremal, False)))None of 32,768 colorings avoids a triangle, all have at least two, and has exactly the 12 pentagon colorings. For enumeration already has colorings; for , needed to confirm by brute force, . Known Ramsey-number proofs combine pigeonhole-style arguments with heavily pruned computer searches.
Finally Lucas’s theorem against exact binomials and the triangle drawn modulo 2 and 3.
from math import comb
import numpy as np
import matplotlib.pyplot as plt
def binom_mod_lucas(n, k, p):
r = 1
while n or k:
ni, ki = n % p, k % p
if ki > ni:
return 0
r = r * comb(ni, ki) % p
n, k = n // p, k // p
return r
ok = all(binom_mod_lucas(n, k, p) == comb(n, k) % p
for p in (2, 3, 5, 7) for n in range(120) for k in range(n + 1))
print("Lucas coincide con comb(n, k) % p para p = 2, 3, 5, 7 y n < 120:", ok)
print("C(n, k) impar <=> k & n == k:",
all((comb(n, k) % 2 == 1) == (k & n == k) for n in range(200) for k in range(n + 1)))
impares = [sum(comb(n, k) % 2 for k in range(n + 1)) for n in range(128)]
print("impares por fila == 2^(unos de n):", all(impares[n] == 2 ** bin(n).count("1") for n in range(128)))
print("impares en la fila 100 =", impares[100], " (100 =", bin(100), ")")
N = 81
fig, ax = plt.subplots(1, 2, figsize=(9, 4.2))
for a, p in zip(ax, (2, 3)):
M = np.full((N, N), np.nan)
for n in range(N):
for k in range(n + 1):
M[n, k] = binom_mod_lucas(n, k, p)
a.imshow(M, cmap="viridis", interpolation="nearest")
a.set_title(f"C(n, k) mod {p}")
a.set_xlabel("k"); a.set_ylabel("n")
plt.tight_layout(); plt.show()The library version
| Function | Returns | Notes |
|---|---|---|
math.comb(n, k), math.perm(n, k), math.factorial(n) | exact integers | Python integers have arbitrary precision: always exact |
itertools.permutations, combinations, combinations_with_replacement, product | lazy generators | lexicographic order by input position |
scipy.special.comb(n, k) | float64 by default | vectorized but approximate; exact=True gives an exact integer |
scipy.special.gammaln, math.lgamma | floating-point | for with large , e.g. likelihoods |
sympy.binomial, sympy.subfactorial, sympy.functions.combinatorial.numbers.stirling | exact expressions | symbolic too |
import math, itertools
from scipy.special import comb as scomb, gammaln
import sympy
from sympy.functions.combinatorial.numbers import stirling
print("math.comb(52, 5) =", math.comb(52, 5), " math.perm(10, 3) =", math.perm(10, 3))
print("itertools:", len(list(itertools.combinations(range(10), 3))), "combinaciones de 10 en 3")
print("scipy.special.comb(52, 5) =", scomb(52, 5), " con exact=True:", scomb(52, 5, exact=True))
primero = next(n for n in range(2, 300) if scomb(n, n // 2) != math.comb(n, n // 2))
print(f"\nprimer n con comb(n, n//2) en float distinto del exacto: n = {primero}")
for n in (primero, 100, 1000):
exacto = math.comb(n, n // 2)
aprox = scomb(n, n // 2)
print(f" n = {n:4d}: error relativo de float = {abs(aprox - exacto) / exacto:.1e}"
f" error absoluto ≈ {abs(int(aprox) - exacto):.3g}")
print("C(1030, 515) en float:", scomb(1030, 515), " exacto: un entero de",
len(str(math.comb(1030, 515))), "cifras")
log_c = gammaln(1031) - 2 * gammaln(516)
print(f"log10 C(1030, 515) con gammaln: {log_c / math.log(10):.6f}"
f" exacto: {math.log10(math.comb(1030, 515)):.6f}")
print("\nsympy:", sympy.subfactorial(6), "desarreglos de 6;",
sympy.binomial(52, 5), "manos de póker;",
math.factorial(3) * stirling(6, 3), "sobreyecciones de 6 en 3")Three observations. First, float64 binomials are unreliable even below : scipy.special.comb(33, 16) already differs by one from , because intermediate products and quotients round; above the exact result may not even be representable (consecutive float64 values are 2 or more apart). Relative error remains between and , but absolute error grows with the number ( units for ), and an alternating sum such as inclusion–exclusion cancels huge terms to leave a small result, turning it into nonsense. Second, exceeds float64 maximum , and scipy returns inf; for probability use logarithms (gammaln) or ratios simplified before evaluation. Third, pure Python math.comb is exact and fast; floating point makes sense when vectorizing over NumPy arrays and accepting error, as discussed in floating-point representation.
Common mistakes
Exercises
Step 1 of 4. Which set do you count?
Step 1 of 4. What property of each number do you use?
surjections(n, k), the number of surjective functions from an n-element set to a k-element set, using inclusion–exclusion and exact integers (math.comb and integer powers). It must return 1 for n = k = 0, 0 if k > n or k = 0 < n, and work for large values such as surjections(200, 60) without losing a digit.from math import comb
def surjections(n, k):
"""Número de funciones sobreyectivas de un conjunto de n elementos en uno de k."""
# tu código: suma alternada sobre j de (-1)^j C(k, j) (k - j)^n
return 0Summary
- Sum, product, bijection and quotient rules yield four selection formulas: , , and . Dividing by works only if every class has elements, which fails with repetition.
- Stars and bars: with has solutions; lower bounds use substitution and upper bounds inclusion–exclusion.
- The binomial theorem counts words after commuting; it and double counting yield Pascal, hockey stick, Vandermonde and absorption. Modulo a prime, Lucas reduces to base- digits.
- Pigeonhole (and its version) proves existence without construction: hash collisions, impossibility of compressing everything, Erdős–Szekeres and .
- Inclusion–exclusion counts what avoids every bad property: derangements (), surjections (), and bounded stars and bars. Truncated, it gives Bonferroni and union bounds.
- Check each formula against small brute-force cases and use exact integers: floating-point binomials lose digits (even below ) and overflow near .