Discrete Math with Python
Python is a very good calculator for discrete mathematics. Its integers have unlimited size, it has exact fractions, and its standard library can generate every subset, permutation or combination of a small set. This lesson is a tour of the tools the rest of the course uses.
Exact integers and fractions
A Python int never overflows: or are computed exactly. For probabilities and ratios, fractions.Fraction keeps results exact instead of rounding them like a float.
from fractions import Fraction
from math import factorial, comb, gcd
print("2^100 =", 2 ** 100)
print("30! =", factorial(30))
print("C(52, 5) =", comb(52, 5))
print("gcd(84, 120) =", gcd(84, 120))
p = Fraction(1, 6) + Fraction(1, 3)
print("1/6 + 1/3 =", p, " as float:", float(p))
print("0.1 + 0.2 == 0.3 ?", 0.1 + 0.2 == 0.3, " exact:", Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10))2^100 = 1267650600228229401496703205376
30! = 265252859812191058636308480000000
C(52, 5) = 2598960
gcd(84, 120) = 12
1/6 + 1/3 = 1/2 as float: 0.5
0.1 + 0.2 == 0.3 ? False exact: True
Integer division and remainder are // and %. For a positive divisor, Python's % always returns a remainder between and , which matches the mathematical definition used in number theory: , so -7 % 3 is 2.
Sets, tuples and itertools
Python set objects behave like mathematical sets: no order, no duplicates, with union |, intersection &, difference - and symmetric difference ^. Tuples model ordered sequences. The itertools module lists the objects that counting problems are about.
| Math | Python |
|---|---|
| (Cartesian product) | itertools.product(A, B) |
| ordered arrangements of items | itertools.permutations(A, k) |
| -element subsets | itertools.combinations(A, k) |
| all subsets (the power set) | combinations for every |
from itertools import product, permutations, combinations
A = {1, 2, 3}
B = {3, 4}
print("A | B =", A | B, " A & B =", A & B, " A - B =", A - B)
print("A x B =", sorted(product(A, B)))
print("permutations of 'abc':", ["".join(p) for p in permutations("abc")])
power = [set(c) for k in range(len(A) + 1) for c in combinations(sorted(A), k)]
print("power set of A:", power, "->", len(power), "subsets")A | B = {1, 2, 3, 4} A & B = {3} A - B = {1, 2}
A x B = [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
permutations of 'abc': ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
power set of A: [set(), {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}] -> 8 subsets
Brute-force checks over all cases
Many statements in discrete math are about finitely many cases. Then a loop over every case is a real proof, called proof by exhaustion. For example, a square of an integer always leaves remainder 0 or 1 when divided by 4: since only depends on , checking settles it for all integers.
residues = {n: (n * n) % 4 for n in range(4)}
print("n mod 4 -> n^2 mod 4:", residues)
print("possible remainders of a square mod 4:", sorted(set(residues.values())))n mod 4 -> n^2 mod 4: {0: 0, 1: 1, 2: 0, 3: 1}
possible remainders of a square mod 4: [0, 1]
SymPy for number theory and logic
SymPy has helpers for primes, factorization, modular inverses and Boolean formulas. They are useful for checking hand calculations.
from sympy import factorint, isprime, primerange, mod_inverse
from sympy.logic.boolalg import to_cnf
from sympy.abc import p, q
print("factor 360:", factorint(360))
print("is 2^31 - 1 prime?", isprime(2 ** 31 - 1))
print("primes below 30:", list(primerange(2, 30)))
print("inverse of 7 mod 26:", mod_inverse(7, 26))
print("CNF of p -> q:", to_cnf(p >> q))factor 360: {2: 3, 3: 2, 5: 1}
is 2^31 - 1 prime? True
primes below 30: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
inverse of 7 mod 26: 15
CNF of p -> q: q | ~p
factorint(360) returns {2: 3, 3: 2, 5: 1}, meaning . In SymPy, p >> q builds the implication , and its conjunctive normal form is .
Note: Each playground runs on its own, so every example imports what it needs.
Exercises
Exercise 1: Big numbers
Compute exactly and the number of decimal digits of .
Answer
; has 158 digits.
Solution
Python integers are exact, so converting to a string and taking its length counts the digits.
from math import factorial
print(2 ** 64)
print(len(str(factorial(100))))18446744073709551616
158
Exercise 2: Subsets of a given size
How many 2-element subsets does have? List them with itertools.
Answer
6: .
Solution
combinations produces each subset once, in sorted order, as a tuple.
from itertools import combinations
subs = list(combinations("abcd", 2))
print(len(subs), subs)6 [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
Exercise 3: Proof by exhaustion
Show that is divisible by 6 for every integer by checking the remainders of modulo 6.
Answer
For every remainder , , so for all .
Solution
only depends on , because sums and products of remainders give the remainder of sums and products. So six cases cover all integers, negative ones included.
print([(r, (r ** 3 - r) % 6) for r in range(6)])[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0)]
Algebraically: is a product of three consecutive integers, so one factor is even and one is a multiple of 3.
Test yourself
What does -7 % 3 return in Python?
- -1
- 1
- 2
- -2
Which itertools function lists the -element subsets of a collection?
productpermutationscombinationsaccumulate
When is checking every case with a loop a valid proof?
- Never
- When the statement only involves finitely many cases and the loop covers all of them
- When the loop runs at least a million times
- Only when SymPy is used