Discrete Math Exercises
Time to practise the whole course. Each exercise has a starter program that runs but doesn't do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.
Tip: Work a tiny case by hand first (three variables, a six-vertex graph, ), then let the code check the general case. A brute-force check over all small inputs is the discrete mathematician's best friend.
| # | Exercise | Practises |
|---|---|---|
| 1 | Is the argument valid? | truth tables, implication, validity |
| 2 | Modular inverses with Euclid | extended Euclid, Bézout coefficients |
| 3 | Sieve of Eratosthenes | primes, the prime number theorem |
| 4 | Fast modular exponentiation | repeated squaring, binary expansion |
| 5 | Topological sort | DAGs, in-degrees, scheduling |
| 6 | Is the graph bipartite? | 2-coloring, BFS, odd cycles |
| 7 | Derangements | inclusion-exclusion, brute-force check |
| 8 | Strings without "11" | recurrences, Fibonacci |
Exercise 1: Is the argument valid?
An argument "if and then " is valid when is true in every row of the truth table (Equivalence and Validity). Check two arguments: (a) from and conclude ; (b) from and conclude . The starter's valid always says yes.
from itertools import product
implies = lambda a, b: (not a) or b
def valid(premises, conclusion, nvars):
# TODO: return False if some assignment makes all premises true and the conclusion false
return True
chain = valid([lambda p, q, r: implies(p, q), lambda p, q, r: implies(q, r)],
lambda p, q, r: implies(p, r), 3)
converse = valid([lambda p, q: implies(p, q), lambda p, q: q], lambda p, q: p, 2)
print("chain rule valid:", chain)
print("affirming the consequent valid:", converse)chain rule valid: True
affirming the consequent valid: True
Expected output when solved:
chain rule valid: True
affirming the consequent valid: FalseThe chain rule (hypothetical syllogism) is valid; "affirming the consequent" is a classic fallacy, refuted by the row false, true.
Hint: Loop over
product([False, True], repeat=nvars)and testall(f(*v) for f in premises) and not conclusion(*v).
Solution
from itertools import product
implies = lambda a, b: (not a) or b
def valid(premises, conclusion, nvars):
for v in product([False, True], repeat=nvars):
if all(f(*v) for f in premises) and not conclusion(*v):
return False
return True
chain = valid([lambda p, q, r: implies(p, q), lambda p, q, r: implies(q, r)],
lambda p, q, r: implies(p, r), 3)
converse = valid([lambda p, q: implies(p, q), lambda p, q: q], lambda p, q: p, 2)
print("chain rule valid:", chain)
print("affirming the consequent valid:", converse)chain rule valid: True
affirming the consequent valid: False
Exercise 2: Modular inverses with Euclid
Write the extended Euclidean algorithm (GCD) returning with , then use it to find inverses modulo 101 (Modular Inverses). The starter returns dummy values.
def ext_gcd(a, b):
# TODO: recursive extended Euclid: if b == 0 return (a, 1, 0)
return (1, 0, 0)
def inverse(a, m):
g, s, t = ext_gcd(a, m)
return s % m if g == 1 else None
for a in [2, 7, 50, 100]:
inv = inverse(a, 101)
print(a, inv, (a * inv) % 101 if inv is not None else "-")
print(ext_gcd(240, 46))2 0 0
7 0 0
50 0 0
100 0 0
(1, 0, 0)
Expected output when solved:
2 51 1
7 29 1
50 99 1
100 100 1
(2, -9, 47)Each product is 1 modulo 101, and .
Hint: If
ext_gcd(b, a % b)returns(g, s, t), then(g, t, s - (a // b) * t)works for(a, b).
Solution
def ext_gcd(a, b):
if b == 0:
return (a, 1, 0)
g, s, t = ext_gcd(b, a % b)
return (g, t, s - (a // b) * t)
def inverse(a, m):
g, s, t = ext_gcd(a, m)
return s % m if g == 1 else None
for a in [2, 7, 50, 100]:
inv = inverse(a, 101)
print(a, inv, (a * inv) % 101 if inv is not None else "-")
print(ext_gcd(240, 46))2 51 1
7 29 1
50 99 1
100 100 1
(2, -9, 47)
Exercise 3: Sieve of Eratosthenes
List the primes below by crossing out multiples (Primes), then compare the count with the estimate . The starter marks every number from 2 on as prime.
import math
def sieve(N):
is_prime = [False, False] + [True] * (N - 2)
# TODO: for each p with p * p < N that is still marked prime, cross out p*p, p*p+p, ...
return [i for i in range(N) if is_prime[i]]
ps = sieve(100)
print(ps[:12])
for N in [100, 1000, 10000, 100000]:
print(N, len(sieve(N)), round(N / math.log(N)))[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
100 98 22
1000 998 145
10000 9998 1086
100000 99998 8686
Expected output when solved:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
100 25 22
1000 168 145
10000 1229 1086
100000 9592 8686The ratio falls slowly toward 1, as the prime number theorem promises.
Hint:
is_prime[p * p::p] = [False] * len(range(p * p, N, p))crosses out a whole slice at once.
Solution
import math
def sieve(N):
is_prime = [False, False] + [True] * (N - 2)
p = 2
while p * p < N:
if is_prime[p]:
is_prime[p * p::p] = [False] * len(range(p * p, N, p))
p += 1
return [i for i in range(N) if is_prime[i]]
ps = sieve(100)
print(ps[:12])
for N in [100, 1000, 10000, 100000]:
print(N, len(sieve(N)), round(N / math.log(N)))[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
100 25 22
1000 168 145
10000 1229 1086
100000 9592 8686
Exercise 4: Fast modular exponentiation
RSA needs for exponents with hundreds of digits (RSA). Repeated squaring reads in binary: square for every bit, multiply when the bit is 1, so it needs about multiplications. Count them. The starter multiplies times, which is hopeless for big , so it is only tried on a small one.
def power_mod(a, e, n):
result, mults = 1, 0
# TODO: replace this loop by repeated squaring
for _ in range(e):
result = result * a % n
mults += 1
return result, mults
print(power_mod(7, 1000, 13), pow(7, 1000, 13))
e = 2 ** 64 + 12345
print("big exponent: skipped") # TODO: print(power_mod(5, e, 1000003), pow(5, e, 1000003))(9, 1000) 9
big exponent: skipped
Expected output when solved:
(9, 16) 9
(795388, 72) 795388Hint: While
e > 0: ife & 1, multiplyresultbya; then squareaand shifte >>= 1. Count both kinds of multiplication.
Solution
def power_mod(a, e, n):
result, mults = 1, 0
a %= n
while e > 0:
if e & 1:
result = result * a % n
mults += 1
a = a * a % n
mults += 1
e >>= 1
return result, mults
print(power_mod(7, 1000, 13), pow(7, 1000, 13))
e = 2 ** 64 + 12345
print(power_mod(5, e, 1000003), pow(5, e, 1000003))(9, 16) 9
(795388, 72) 795388
Exercise 5: Topological sort
Order the tasks of a small build so that every task comes after its prerequisites (DAGs and Scheduling). Kahn's algorithm repeatedly takes a task with no unfinished prerequisites. Use the alphabetically first available task each time so the answer is unique. The starter just sorts the names.
import heapq
deps = { # task: prerequisites
"compile": ["fetch", "configure"],
"configure": ["fetch"],
"docs": ["compile"],
"fetch": [],
"link": ["compile"],
"package": ["link", "docs", "test"],
"test": ["link"],
}
def topo_order(deps):
# TODO: Kahn's algorithm with a heap of ready tasks (in-degree 0)
return sorted(deps)
order = topo_order(deps)
print(order)
pos = {t: i for i, t in enumerate(order)}
print("valid:", all(pos[p] < pos[t] for t in deps for p in deps[t]))['compile', 'configure', 'docs', 'fetch', 'link', 'package', 'test']
valid: False
Expected output when solved:
['fetch', 'configure', 'compile', 'docs', 'link', 'test', 'package']
valid: TrueHint: Count unfinished prerequisites per task, push the tasks with count 0 onto a heap, and when you pop a task, decrease the count of every task that depends on it.
Solution
import heapq
deps = { # task: prerequisites
"compile": ["fetch", "configure"],
"configure": ["fetch"],
"docs": ["compile"],
"fetch": [],
"link": ["compile"],
"package": ["link", "docs", "test"],
"test": ["link"],
}
def topo_order(deps):
remaining = {t: len(ps) for t, ps in deps.items()}
users = {t: [] for t in deps}
for t, ps in deps.items():
for p in ps:
users[p].append(t)
ready = [t for t, k in remaining.items() if k == 0]
heapq.heapify(ready)
order = []
while ready:
t = heapq.heappop(ready)
order.append(t)
for u in users[t]:
remaining[u] -= 1
if remaining[u] == 0:
heapq.heappush(ready, u)
return order if len(order) == len(deps) else None # None means a cycle
order = topo_order(deps)
print(order)
pos = {t: i for i, t in enumerate(order)}
print("valid:", all(pos[p] < pos[t] for t in deps for p in deps[t]))['fetch', 'configure', 'compile', 'docs', 'link', 'test', 'package']
valid: True
Exercise 6: Is the graph bipartite?
A graph is bipartite exactly when it has no odd cycle, and breadth-first search finds a 2-coloring or proves none exists (Graph Coloring). Test a 6-cycle, a 5-cycle and a grid graph. The starter answers yes every time.
from collections import deque
def cycle(n):
return {i: [(i - 1) % n, (i + 1) % n] for i in range(n)}
def grid(k):
g = {(r, c): [] for r in range(k) for c in range(k)}
for r, c in g:
for dr, dc in [(1, 0), (0, 1)]:
if (r + dr, c + dc) in g:
g[(r, c)].append((r + dr, c + dc))
g[(r + dr, c + dc)].append((r, c))
return g
def two_color(g):
color = {}
# TODO: BFS from every uncolored vertex; give neighbours the opposite color;
# return None if an edge joins two vertices of the same color
return color
for name, g in [("C6", cycle(6)), ("C5", cycle(5)), ("grid 3x3", grid(3))]:
col = two_color(g)
print(name, "bipartite" if col is not None else "not bipartite",
"" if col is None else sum(col.values()))C6 bipartite 0
C5 bipartite 0
grid 3x3 bipartite 0
Expected output when solved:
C6 bipartite 3
C5 not bipartite
grid 3x3 bipartite 4The last number is how many vertices got color 1: half of , and 4 of the 9 grid cells (the cells with odd).
Hint: Start each BFS with
color[s] = 0; for an edgeu -> v, setcolor[v] = 1 - color[u]ifvis new, and fail ifcolor[v] == color[u].
Solution
from collections import deque
def cycle(n):
return {i: [(i - 1) % n, (i + 1) % n] for i in range(n)}
def grid(k):
g = {(r, c): [] for r in range(k) for c in range(k)}
for r, c in g:
for dr, dc in [(1, 0), (0, 1)]:
if (r + dr, c + dc) in g:
g[(r, c)].append((r + dr, c + dc))
g[(r + dr, c + dc)].append((r, c))
return g
def two_color(g):
color = {}
for s in g:
if s in color:
continue
color[s] = 0
queue = deque([s])
while queue:
u = queue.popleft()
for v in g[u]:
if v not in color:
color[v] = 1 - color[u]
queue.append(v)
elif color[v] == color[u]:
return None
return color
for name, g in [("C6", cycle(6)), ("C5", cycle(5)), ("grid 3x3", grid(3))]:
col = two_color(g)
print(name, "bipartite" if col is not None else "not bipartite",
"" if col is None else sum(col.values()))C6 bipartite 3
C5 not bipartite
grid 3x3 bipartite 4
Exercise 7: Derangements
A derangement is a permutation with no fixed point: nobody gets their own hat back. By inclusion-exclusion,
Implement the formula, check it by brute force for small , and watch approach . The starter's formula keeps only the term.
import math
from itertools import permutations
def derangements(n):
# TODO: sum over k = 0..n of (-1)**k * comb(n, k) * factorial(n - k)
return math.factorial(n)
def brute(n):
return sum(1 for p in permutations(range(n)) if all(p[i] != i for i in range(n)))
print([derangements(n) for n in range(1, 8)])
print([brute(n) for n in range(1, 8)])
print(round(derangements(12) / math.factorial(12), 8), round(1 / math.e, 8))[1, 2, 6, 24, 120, 720, 5040]
[0, 1, 2, 9, 44, 265, 1854]
1.0 0.36787944
Expected output when solved:
[0, 1, 2, 9, 44, 265, 1854]
[0, 1, 2, 9, 44, 265, 1854]
0.36787944 0.36787944Hint:
sum((-1) ** k * math.comb(n, k) * math.factorial(n - k) for k in range(n + 1)).
Solution
import math
from itertools import permutations
def derangements(n):
return sum((-1) ** k * math.comb(n, k) * math.factorial(n - k) for k in range(n + 1))
def brute(n):
return sum(1 for p in permutations(range(n)) if all(p[i] != i for i in range(n)))
print([derangements(n) for n in range(1, 8)])
print([brute(n) for n in range(1, 8)])
print(round(derangements(12) / math.factorial(12), 8), round(1 / math.e, 8))[0, 1, 2, 9, 44, 265, 1854]
[0, 1, 2, 9, 44, 265, 1854]
0.36787944 0.36787944
Exercise 8: Strings without "11"
Count the binary strings of length with no two adjacent 1s. Split on the first character: a string starting with 0 continues with any valid string of length ; one starting with 1 must continue with 0 and then any valid string of length . So with , (Recurrences). The starter only has the brute-force count.
from itertools import product
def brute(n):
return sum(1 for s in product("01", repeat=n) if "11" not in "".join(s))
def by_recurrence(n):
# TODO: iterate a_n = a_(n-1) + a_(n-2) from a_1 = 2, a_2 = 3
return 0
print([brute(n) for n in range(1, 13)])
print([by_recurrence(n) for n in range(1, 13)])
print(by_recurrence(80))[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
0
Expected output when solved:
[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
61305790721611591These are Fibonacci numbers shifted by two places, , and the recurrence handles , where brute force would need strings.
Hint: Keep two variables
a, b = 2, 3and stepa, b = b, a + b.
Solution
from itertools import product
def brute(n):
return sum(1 for s in product("01", repeat=n) if "11" not in "".join(s))
def by_recurrence(n):
a, b = 2, 3
for _ in range(n - 1):
a, b = b, a + b
return a
print([brute(n) for n in range(1, 13)])
print([by_recurrence(n) for n in range(1, 13)])
print(by_recurrence(80))[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
61305790721611591
Test yourself
Which assignment refutes "from and , conclude "?
- true, true
- false, true
- true, false
- false, false
About how many multiplications does repeated squaring need for an exponent near ?
- About 64 to 128
- About 2^32
- About 2^64
- Exactly 64 squared
A graph has no 2-coloring exactly when it contains…
- a vertex of degree 3
- a cycle of odd length
- a cycle of even length
- more edges than vertices
Where next
You have used every chapter of the course: logic, number theory, graphs, counting and recurrences. The Mini Project combines DAGs, coloring and counting in one program. For the probability side, continue with Probability Theory; for algorithms built on these ideas, see the DSA course.