Mini Project: A Course Scheduler
A university department has to answer three questions every year. In what order can students take the courses, and how many semesters does the programme need? How many exam slots are needed so that no student has two exams at once? And how much freedom do students have in choosing their order? Each question is a chapter of this course: DAGs and scheduling, graph coloring and counting. In this project you answer all three for a made-up programme of ten courses.
What we are building:
| Step | Question | Concepts |
|---|---|---|
| 1. The prerequisite graph | Is the plan consistent? | digraphs, cycle detection, topological sort |
| 2. Semesters | How many semesters, with at most 2 courses each? | longest paths, antichains, greedy scheduling |
| 3. Exam slots | How few exam slots avoid clashes? | conflict graph, greedy coloring, cliques |
| 4. Counting orders | How many valid course orders exist? | linear extensions, DP over subsets, brute-force check |
Note: Each step is a complete program (the playground does not share variables between runs), so the data and helpers are repeated where needed.
Step 1: The prerequisite graph
Each course lists its prerequisites. Drawing an edge from each prerequisite to the course gives a directed graph, and a plan is only possible if this graph is a DAG: a cycle (A needs B, B needs A) could never be scheduled. Kahn's algorithm finds a topological order or reports a cycle.
prereq = {
"Intro": [],
"Logic": ["Intro"],
"Sets": ["Intro"],
"Proofs": ["Logic", "Sets"],
"NumTheory": ["Proofs"],
"Graphs": ["Proofs"],
"Counting": ["Sets"],
"Probability": ["Counting"],
"Algorithms": ["Graphs", "Counting"],
"Crypto": ["NumTheory", "Probability"],
}
def topo_order(prereq):
remaining = {c: len(ps) for c, ps in prereq.items()}
ready = sorted(c for c, k in remaining.items() if k == 0)
order = []
while ready:
c = ready.pop(0)
order.append(c)
for d in sorted(prereq):
if c in prereq[d]:
remaining[d] -= 1
if remaining[d] == 0:
ready.append(d)
ready.sort()
return order if len(order) == len(prereq) else None
edges = sum(len(ps) for ps in prereq.values())
print(len(prereq), "courses,", edges, "prerequisite edges")
print("order:", topo_order(prereq))
broken = dict(prereq, Intro=["Crypto"]) # a mistake in the catalogue
print("with Intro needing Crypto:", topo_order(broken))10 courses, 12 prerequisite edges
order: ['Intro', 'Logic', 'Sets', 'Counting', 'Probability', 'Proofs', 'Graphs', 'Algorithms', 'NumTheory', 'Crypto']
with Intro needing Crypto: None
A single bad entry creates a cycle through the whole programme, and the algorithm detects it because some courses never reach zero remaining prerequisites.
Step 2: Semesters
Without a limit on courses per semester, each course can be taken one semester after the latest of its prerequisites. That is the length of the longest chain ending at the course, and the number of semesters needed is the length of the longest chain overall: the critical path. Courses in the same semester form an antichain (none is a prerequisite of another).
With a limit of 2 courses per semester the greedy rule "each semester, take up to 2 available courses, preferring those that start the longest remaining chains" is a good heuristic. (Optimal scheduling with a width limit is NP-hard in general, but the critical path and are lower bounds we can compare against.)
from functools import lru_cache
import math
prereq = {
"Intro": [], "Logic": ["Intro"], "Sets": ["Intro"], "Proofs": ["Logic", "Sets"],
"NumTheory": ["Proofs"], "Graphs": ["Proofs"], "Counting": ["Sets"],
"Probability": ["Counting"], "Algorithms": ["Graphs", "Counting"],
"Crypto": ["NumTheory", "Probability"],
}
users = {c: [d for d in prereq if c in prereq[d]] for c in prereq}
@lru_cache(None)
def level(c): # longest chain ending at c
return 1 + max((level(p) for p in prereq[c]), default=0)
@lru_cache(None)
def tail(c): # longest chain starting at c
return 1 + max((tail(u) for u in users[c]), default=0)
semesters = max(level(c) for c in prereq)
print("unlimited:", semesters, "semesters")
for s in range(1, semesters + 1):
print(f" semester {s}:", sorted(c for c in prereq if level(c) == s))
done, plan, limit = set(), [], 2
while len(done) < len(prereq):
ready = [c for c in prereq if c not in done and all(p in done for p in prereq[c])]
ready.sort(key=lambda c: (-tail(c), c))
take = ready[:limit]
plan.append(take)
done.update(take)
print(f"at most {limit} per semester:", len(plan), "semesters")
for s, take in enumerate(plan, 1):
print(f" semester {s}:", take)
print("lower bound:", max(semesters, math.ceil(len(prereq) / limit)))unlimited: 5 semesters
semester 1: ['Intro']
semester 2: ['Logic', 'Sets']
semester 3: ['Counting', 'Proofs']
semester 4: ['Graphs', 'NumTheory', 'Probability']
semester 5: ['Algorithms', 'Crypto']
at most 2 per semester: 6 semesters
semester 1: ['Intro']
semester 2: ['Logic', 'Sets']
semester 3: ['Counting', 'Proofs']
semester 4: ['Graphs', 'NumTheory']
semester 5: ['Probability', 'Algorithms']
semester 6: ['Crypto']
lower bound: 5
The greedy plan needs 6 semesters while both lower bounds say 5. Here the greedy plan is optimal anyway: semester 1 can only hold Intro, because every other course depends on it, so the remaining 9 courses need at least more semesters. Lower bounds are not always reachable, and a sharper argument closed the gap.
Step 3: Exam slots
Two courses conflict if some student takes both this year; their exams must go in different slots. Build the conflict graph (courses are vertices, conflicts are edges) and color it: colors are exam slots. Greedy coloring in order of decreasing degree gives an upper bound. Any clique (a set of pairwise-conflicting courses) needs that many different slots, so the largest clique is a lower bound. When the two bounds meet, the schedule is provably optimal.
from itertools import combinations
students = [
["Logic", "Sets", "Counting"],
["Proofs", "Counting", "Graphs"],
["Proofs", "NumTheory"],
["Graphs", "Probability", "Algorithms"],
["NumTheory", "Probability", "Crypto"],
["Logic", "Proofs"],
["Counting", "Algorithms"],
["Sets", "Probability"],
["Intro", "Logic"],
]
courses = sorted({c for s in students for c in s})
adj = {c: set() for c in courses}
for s in students:
for a, b in combinations(s, 2):
adj[a].add(b)
adj[b].add(a)
print(len(courses), "courses,", sum(len(v) for v in adj.values()) // 2, "conflicts")
order = sorted(courses, key=lambda c: (-len(adj[c]), c))
slot = {}
for c in order:
used = {slot[d] for d in adj[c] if d in slot}
slot[c] = min(k for k in range(len(courses)) if k not in used)
slots = max(slot.values()) + 1
print("greedy uses", slots, "slots")
for k in range(slots):
print(f" slot {k + 1}:", sorted(c for c in courses if slot[c] == k))
def is_clique(group):
return all(b in adj[a] for a, b in combinations(group, 2))
best = max((g for r in range(1, 6) for g in combinations(courses, r) if is_clique(g)), key=len)
print("largest clique:", list(best), "-> at least", len(best), "slots")
print("valid:", all(slot[a] != slot[b] for a in adj for b in adj[a]))10 courses, 17 conflicts
greedy uses 3 slots
slot 1: ['Counting', 'Intro', 'Probability']
slot 2: ['Graphs', 'Logic', 'NumTheory']
slot 3: ['Algorithms', 'Crypto', 'Proofs', 'Sets']
largest clique: ['Algorithms', 'Counting', 'Graphs'] -> at least 3 slots
valid: True
Step 4: Counting orders
If a student takes one course at a time, how many different orders respect all prerequisites? These orders are the linear extensions of the partial order. There is no simple formula, but a DP over subsets works: let be the number of ways to finish exactly the set of courses (in a valid order). Build the sets up one course at a time: a course can be added to when all its prerequisites are already in .
This visits each of the subsets once, while brute force would test permutations. As a check, brute force is still feasible on the first seven courses ().
from itertools import permutations
prereq = {
"Intro": [], "Logic": ["Intro"], "Sets": ["Intro"], "Proofs": ["Logic", "Sets"],
"NumTheory": ["Proofs"], "Graphs": ["Proofs"], "Counting": ["Sets"],
"Probability": ["Counting"], "Algorithms": ["Graphs", "Counting"],
"Crypto": ["NumTheory", "Probability"],
}
def count_orders(prereq):
names = list(prereq)
idx = {c: i for i, c in enumerate(names)}
need = [sum(1 << idx[p] for p in prereq[c]) for c in names]
n = len(names)
f = [0] * (1 << n)
f[0] = 1
for S in range(1 << n): # subsets in increasing order: S before S | bit
if f[S] == 0:
continue
for i in range(n):
if not S >> i & 1 and need[i] & S == need[i]:
f[S | 1 << i] += f[S]
return f[-1]
def brute(prereq):
total = 0
for p in permutations(prereq):
pos = {c: i for i, c in enumerate(p)}
total += all(pos[q] < pos[c] for c in prereq for q in prereq[c])
return total
small = {c: prereq[c] for c in list(prereq)[:7]}
print("first 7 courses: DP", count_orders(small), " brute force", brute(small))
print("all 10 courses:", count_orders(prereq), "valid orders out of 3628800")first 7 courses: DP 18 brute force 18
all 10 courses: 164 valid orders out of 3628800
Only a small fraction of all permutations respect the prerequisites. The same subset DP counts schedules in compilers (instruction orderings), build systems and project planning, and with probabilities instead of counts it computes the chance that a random valid order puts one course before another.
Ideas to extend it
- Add a semester limit to Step 4 and count the plans with at most 2 courses per semester.
- Give each course a credit value and schedule semesters with a credit cap (a bin-packing flavour of the problem).
- Make exam slots respect a second rule: no student has two exams in consecutive slots (a coloring of a different graph).
- Replace the brute-force clique search by the Bron–Kerbosch algorithm and try a catalogue of 40 courses.
Test yourself
Without a limit per semester, the minimum number of semesters equals…
- the number of courses
- the length of the longest prerequisite chain
- the largest number of prerequisites of one course
- the number of exam slots
Greedy coloring uses 4 exam slots and the conflict graph has a 4-clique. What follows?
- 4 slots is optimal
- 3 slots might be possible
- The graph is planar
- Nothing
Why is the subset DP for counting valid orders faster than brute force?
- It uses floating point
- It visits subsets instead of permutations
- It ignores prerequisites
- It samples randomly