Sub topic 14
Putting the three modules together
This chapter combines math, random, and datetime in one small program. It assumes you have read the earlier chapters on each module. You should know math.comb and math.ceil, seeded random.Random instances, and date plus timedelta arithmetic.
Why combine them
Real tasks rarely stay inside one module. Scheduling, simulation, test-data generation, and reporting all mix counting, chance, and dates. Each module has a narrow job, so combining them is mostly a matter of passing plain values between them.
| Module | Job in the combined program |
|---|---|
| `math` | Counts items and rounds up |
| `random` | Chooses the order, reproducibly |
| `datetime` | Turns positions into calendar dates |
Worked example: a round-robin schedule
Six teams each play every other team once. The organizers want a random match order, one match per week, starting on Monday 7 December 2026. The order must be reproducible so that everyone sees the same schedule when the script is re-run.
import math
import random
from datetime import date, timedelta
teams = ["Ant", "Bee", "Cat", "Dog", "Elk", "Fox"]
# Every unordered pair of teams plays once.
pairs = [(a, b) for i, a in enumerate(teams) for b in teams[i + 1:]]
print(len(pairs) == math.comb(len(teams), 2)) # True: 15 matches
rng = random.Random(42) # own generator, fixed seed
rng.shuffle(pairs) # shuffles in place
start = date(2026, 12, 7)
for week, (a, b) in enumerate(pairs):
match_day = start + timedelta(weeks=week)
if week < 3:
print(match_day.isoformat(), a, "vs", b)
last = start + timedelta(weeks=len(pairs) - 1)
print("Last match:", last.isoformat()) # 2027-03-15
# With two matches per week, how many weeks are needed?
print(math.ceil(len(pairs) / 2)) # 8The three modules do not call each other. math.comb checks the pair list, rng.shuffle fixes the order, and timedelta(weeks=week) converts each position into a date. Because the shuffle uses random.Random(42), the match order is the same on every run, though the exact pairs it prints depend on the shuffle.
Common errors when combining modules
- Using the global generator. Calling
random.shuffledirectly shares one hidden generator across your whole program. Any other code that draws numbers changes your results. Use your ownrandom.Random(seed)instance, as above. - Float results where integers are needed.
len(pairs) / 2gives7.5, a float. Usemath.ceilto get a whole number of weeks, or//if you want rounding down. - Mixing naive and aware datetimes. The example uses
date, which has no time zone, so it is safe. If you later add kickoff times, make them all aware (for example withzoneinfo), or all naive. Subtracting one kind from the other raisesTypeError. - Using
randomfor secrets. If the schedule had to include invite codes, generate them withsecrets. A seededrandomsequence can be reproduced by anyone who knows the seed. - Comparing floats with
==. If you compute durations or averages with floats, compare withmath.isclose.
Exercise
Exercise
A script builds a list of 10 random dates in 2026 using one seeded random.Random instance and date(2026, 1, 1) + timedelta(days=rng.randrange(365)). Why is randrange(365) correct here, and what changes in a leap year such as 2028?
Show answer
randrange(365) returns an integer from 0 to 364, so the result runs from 1 January to 31 December in a 365-day year. The upper bound is exclusive. In 2028, which has 366 days, 31 December would never be chosen, so use randrange(366). A more robust option is to compute the length with (date(2029, 1, 1) - date(2028, 1, 1)).days.