TExcelTAD
Home › Discrete Mathematics › Discrete Math with Python

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: 22002^{200} or 30!30! are computed exactly. For probabilities and ratios, fractions.Fraction keeps results exact instead of rounding them like a float.

python · try it yourself
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 00 and n−1n - 1, which matches the mathematical definition used in number theory: −7=3⋅(−3)+2-7 = 3 \cdot (-3) + 2, 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
A×BA \times B (Cartesian product) itertools.product(A, B)
ordered arrangements of kk items itertools.permutations(A, k)
kk-element subsets itertools.combinations(A, k)
all subsets (the power set) combinations for every kk
python · try it yourself
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 n2 mod 4n^2 \bmod 4 only depends on n mod 4n \bmod 4, checking n=0,1,2,3n = 0, 1, 2, 3 settles it for all integers.

python · try it yourself
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.

python · try it yourself
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 360=23⋅32⋅5360 = 2^3 \cdot 3^2 \cdot 5. In SymPy, p >> q builds the implication p→qp \to q, and its conjunctive normal form is ¬p∨q\neg p \lor q.

Note: Each playground runs on its own, so every example imports what it needs.

Exercises

Exercise 1: Big numbers

Compute 2642^{64} exactly and the number of decimal digits of 100!100!.

Answer

264=184467440737095516162^{64} = 18446744073709551616; 100!100! has 158 digits.

Solution

Python integers are exact, so converting to a string and taking its length counts the digits.

python · try it yourself
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 {a,b,c,d}\{a, b, c, d\} have? List them with itertools.

Answer

6: {a,b},{a,c},{a,d},{b,c},{b,d},{c,d}\{a,b\}, \{a,c\}, \{a,d\}, \{b,c\}, \{b,d\}, \{c,d\}.

Solution

combinations produces each subset once, in sorted order, as a tuple.

python · try it yourself
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 n3−nn^3 - n is divisible by 6 for every integer nn by checking the remainders of nn modulo 6.

Answer

For every remainder r=0,…,5r = 0, \ldots, 5, r3−r≡0(mod6)r^3 - r \equiv 0 \pmod 6, so 6∣n3−n6 \mid n^3 - n for all nn.

Solution

n3−n mod 6n^3 - n \bmod 6 only depends on n mod 6n \bmod 6, because sums and products of remainders give the remainder of sums and products. So six cases cover all integers, negative ones included.

python · try it yourself
print([(r, (r ** 3 - r) % 6) for r in range(6)])
[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0)]

Algebraically: n3−n=(n−1)n(n+1)n^3 - n = (n - 1)n(n + 1) 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. 1
  3. 2
  4. -2

Which itertools function lists the kk-element subsets of a collection?

  1. product
  2. permutations
  3. combinations
  4. accumulate

When is checking every case with a loop a valid proof?

  1. Never
  2. When the statement only involves finitely many cases and the loop covers all of them
  3. When the loop runs at least a million times
  4. Only when SymPy is used