Sub topic 15
Computing the critical path in code
This chapter turns the forward pass, backward pass and float rules from earlier chapters into a small, reusable Python program. It assumes you can already do those calculations by hand. It also assumes basic Python: dictionaries, loops, functions and exceptions.
What the program has to do
A hand calculation assumes the network is sound and that you work through the tasks in a sensible order. Code has to enforce both assumptions. A reliable implementation does five things in sequence:
- Validate the input: no unknown predecessors, no negative durations, no cycles.
- Put the tasks in an order where every predecessor comes before its successors.
- Run the forward pass in that order.
- Run the backward pass in the reverse order.
- Derive float and read the critical path from the zero-float tasks.
The data model
Each task maps to a pair: its duration and a list of predecessor names. This is the same shape used in the earlier examples.
tasks = {
"A": (3, []),
"B": (2, ["A"]),
"C": (4, ["A"]),
"D": (3, ["B", "C"]),
}A dictionary keyed by task name keeps lookups simple. The cost is that successors are not stored. You must derive them once from the predecessor lists, because the backward pass needs them.
Ordering and validation with Kahn's algorithm
Earlier examples relied on the comment "listed so predecessors come first". Real data does not arrive in that order, so the code computes the order itself. Kahn's algorithm does this and detects cycles as a side effect.
The algorithm counts how many unprocessed predecessors each task has. Tasks with a count of zero go into a queue. Taking a task from the queue decrements the counts of its successors. If the queue empties before every task has been processed, the remaining tasks sit on or behind a cycle.
The complete implementation
The block below runs as shown. It validates the input, runs both passes, computes total and free float, and enumerates every critical path, not just one.
from collections import deque
def topological_order(tasks):
"""Return (order, successors) or raise ValueError on bad input."""
if not tasks:
raise ValueError("no tasks given")
for name, (dur, preds) in tasks.items():
if dur < 0:
raise ValueError(f"{name} has a negative duration")
for p in preds:
if p not in tasks:
raise ValueError(f"{name} depends on unknown task {p}")
if p == name:
raise ValueError(f"{name} depends on itself")
succs = {t: [] for t in tasks}
indegree = {}
for t, (_, preds) in tasks.items():
unique = set(preds) # a repeated predecessor must count once
indegree[t] = len(unique)
for p in unique:
succs[p].append(t)
queue = deque(t for t, d in indegree.items() if d == 0)
order = []
while queue:
t = queue.popleft()
order.append(t)
for s in succs[t]:
indegree[s] -= 1
if indegree[s] == 0:
queue.append(s)
if len(order) != len(tasks):
stuck = sorted(set(tasks) - set(order))
raise ValueError(f"cycle detected; blocked tasks: {stuck}")
return order, succs
def schedule(tasks):
order, succs = topological_order(tasks)
# Forward pass
es, ef = {}, {}
for t in order:
dur, preds = tasks[t]
es[t] = max((ef[p] for p in preds), default=0)
ef[t] = es[t] + dur
end = max(ef.values())
# Backward pass
ls, lf = {}, {}
for t in reversed(order):
lf[t] = min((ls[s] for s in succs[t]), default=end)
ls[t] = lf[t] - tasks[t][0]
total_float = {t: ls[t] - es[t] for t in tasks}
free_float = {
t: min((es[s] for s in succs[t]), default=end) - ef[t] for t in tasks
}
critical = {t for t in tasks if total_float[t] == 0}
return {
"end": end, "es": es, "ef": ef, "ls": ls, "lf": lf,
"total_float": total_float, "free_float": free_float,
"critical": critical, "succs": succs,
}
def critical_paths(tasks, result):
"""Return every start-to-finish path made only of critical tasks."""
es, ef = result["es"], result["ef"]
crit, succs = result["critical"], result["succs"]
paths = []
def walk(task, path):
# Follow only critical successors that start exactly when this task ends
nxt = [s for s in succs[task] if s in crit and es[s] == ef[task]]
if not nxt:
if ef[task] == result["end"]:
paths.append(path)
return
for s in nxt:
walk(s, path + [s])
for t in sorted(crit):
if not tasks[t][1] and es[t] == 0:
walk(t, [t])
return paths
if __name__ == "__main__":
network = {
"A": (3, []),
"B": (4, ["A"]),
"C": (4, ["A"]),
"D": (2, ["B", "C"]),
"E": (1, ["A"]),
}
r = schedule(network)
print(r["end"]) # 9
print(r["total_float"]) # {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 3}
print(r["free_float"]["E"]) # 3
print(critical_paths(network, r)) # [['A', 'B', 'D'], ['A', 'C', 'D']]For this network, B and C are both 4 days long and both feed D. Two paths therefore tie at 9 days, and E has 3 days of float. The one-path walk-back from the spine, which follows a single driving predecessor, would return only one of the two. That is why the code above searches forward through all tied edges.
Design decisions worth understanding
Why a successor map is built once
The backward pass asks, for each task, "which tasks come after me?" Scanning every task's predecessor list each time would cost O(n²) overall. Building the map once keeps the whole computation linear in the number of tasks plus links.
Why free float uses early start
Free float is the delay a task can absorb without moving any successor's earliest start. The code therefore compares against es[s] of the successors, not ls[s]. For a task with no successors, the project end plays the role of the successor's start.
Why the path walk checks `es[s] == ef[task]`
A successor can be critical without being driven by this particular task. Requiring es[s] == ef[task] keeps only the edges where the successor starts the moment this task finishes, so each reported path is a real chain of zero-slack links.
Edge cases and failure modes
| Situation | What happens | Handling |
|---|---|---|
| Cycle in predecessors | Kahn's queue empties early | Raise an error listing blocked tasks |
| Predecessor name misspelled | Lookup would fail mid-pass | Reject during validation with the task and name |
| Repeated predecessor in a list | In-degree counted twice and the task never unlocks | Deduplicate with `set` before counting |
| Zero-duration milestone | Start and finish are equal; works correctly | None needed, but check path walking still ends at the end date |
| Several tasks with no successors | Each is a project end | `end` is the maximum finish, and the others get float |
| Float durations such as 0.1 | Equality tests on float can fail | Use integers (hours, minutes) or compare with `math.isclose` |
| Disconnected sub-network | Both groups are computed independently | Decide whether that is intended before trusting the result |
Testing the implementation
Cross-check the code against cases you can verify by hand.
- Run the spine's four-task network. The end must be 10, the float of B must be 2, and the critical path must be A, C, D.
- Run the tied network above. Expect two paths, and check that every path's durations add up to the project end.
- Feed a cycle such as
{"X": (1, ["Y"]), "Y": (1, ["X"])}and confirm the error. - Assert an invariant on random networks: total float is never negative, and at least one task has zero float.
Limits of this code
The program handles finish-to-start links with no lags and ignores resource limits. Adding lags means changing the forward pass to use ef[p] + lag and the backward pass to subtract the same lag. Other dependency types change which of start or finish you compare. Resource constraints cannot be added by tweaking these formulas, because they need a scheduling heuristic on top of the network analysis. During execution, rerun schedule with actual durations for finished tasks and remaining estimates for open ones, since the critical path can move.
Exercise
A task list is {"P": (2, []), "Q": (5, ["P"]), "R": (3, ["P"]), "S": (1, ["Q", "R"])}. Using the code above, what are the project end, the total float of R, the free float of R, and the critical path?
Show answer
P runs 0 to 2. Q runs 2 to 7 and R runs 2 to 5. S starts at max(7, 5) = 7 and finishes at 8, so the project end is 8. In the backward pass, S has latest start 7. Q has latest finish 7 and latest start 2. R has latest finish 7 and latest start 4, so its total float is 4 - 2 = 2. Its free float is es[S] - ef[R] = 7 - 5 = 2. P has latest finish min(2, 4) = 2, so its float is 0. The critical path is P, Q, S.
Exercise
The input {"M": (2, ["N"]), "N": (3, ["O"]), "O": (1, ["M"])} is passed to schedule. What happens, and why does the program not simply compute a result?
Show answer
topological_order raises a ValueError reporting a cycle, with M, N and O as the blocked tasks. Every task has an unprocessed predecessor, so none ever reaches in-degree zero and the Kahn queue starts empty. A forward pass is impossible because no task has a defined earliest start. Without the check, the code would fail on a missing key or loop forever.