Exercises · Pure Python · Topics: integers, divisibility, primes, modular arithmetic, counting, sequences, combinatorics
Pr. Zouhair el Hadiq
Write a Python function classify(n: int) -> str that returns "even" if $n$ is even and "odd" otherwise.
classify(0) == "even", classify(7) == "odd", classify(-4) == "even".Implement is_prime(n: int) -> bool using trial division up to $\lfloor\sqrt{n}\rfloor$.
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29].math.isqrt(n) from the standard library to compute $\lfloor\sqrt{n}\rfloor$ exactly.Write mod_ops(a, b, m) -> dict that returns a dictionary with keys "add", "sub", and "mul" holding $(a+b)\bmod m$, $(a-b)\bmod m$, and $(a \cdot b)\bmod m$ respectively.
Implement lcm(a, b) using Python's math.gcd, then verify the identity:
$$\gcd(a,b)\times \text{lcm}(a,b) = a \times b$$
Test with pairs $(12,8)$, $(100,75)$, and $(17,13)$. Print the GCD, LCM, and whether the identity holds for each pair.
Write fibonacci(n: int) -> list[int] that generates the first $n$ Fibonacci numbers iteratively (no recursion).
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89].Write divisors(n: int) -> list[int] that returns all positive divisors of $n$ in sorted order.
Implement $C(n,k)$ (n-choose-k) without using math.comb, then verify Pascal's identity:
$$C(n,k) = C(n-1,k-1) + C(n-1,k)$$
Write power_set(s: list) -> list that returns the list of all subsets of $s$.
itertools.combinations to enumerate subsets of each size $k = 0, 1, \ldots, |s|$.Implement sieve(N: int) -> list[int] that returns all primes $\le N$ using the Sieve of Eratosthenes (boolean array).
Write arithmetic(start, step, n) and geometric(start, ratio, n) that each return a list of $n$ terms.
Write brute_truth_table(expr_fn, var_names) that prints a truth table for any boolean function of $n$ variables by enumerating all $2^n$ combinations.
itertools.product([False, True], repeat=n) to generate rows.