Sub topic 1
Modeling Dependencies as Directed Graphs
Many real problems involve things that must happen before other things. A course has prerequisites. A source file needs a header to compile first. A database migration needs the table it changes to exist. Before you can order these tasks, you need a precise model of the "before" relationships. A directed graph gives you that model, and the rest of this tutorial runs on top of it.
This chapter covers how to turn a dependency description into a graph, which edge direction to choose, how to store the graph in Python, and the modeling mistakes that cause wrong or confusing results later.
Prerequisites
This chapter assumes you are comfortable with:
- Basic Python syntax, including dictionaries, lists, sets, and loops.
- Graph terminology: vertices (nodes), edges, and directed edges.
- The adjacency list representation of a graph.
- Breadth-first and depth-first search, at the level of knowing what each one visits.
- Big-O notation.
- Queues, stacks, and recursion.
You do not need to know any topological sort algorithm yet. Later chapters build those algorithms on the representation defined here.
From "Depends On" to Edges
A dependency is a statement of the form "A must come before B." In a directed graph, each task becomes a node, and each such statement becomes a directed edge A -> B. An edge points from the thing that must happen first to the thing that waits for it.
Consider a small course catalog:
- Intro to Programming is required for Data Structures and for Discrete Math.
- Data Structures and Discrete Math are both required for Algorithms.
As "before" pairs, that is:
| Before | After |
|---|---|
| intro | data_structures |
| intro | discrete_math |
| discrete_math | algorithms |
| data_structures | algorithms |
Two terms come up constantly. The in-degree of a node is the number of edges pointing into it. The out-degree is the number of edges leaving it. In this graph, intro has in-degree 0 because nothing is required before it, and algorithms has in-degree 2. A node with in-degree 0 can be started right away, and later chapters rely on this fact.
Choosing an Edge Direction
The same dependencies can be drawn with arrows going either way, and both conventions show up in real code. Mixing them up is the most common modeling bug.
| Convention | Edge `u -> v` means | Dictionary maps each node to | Where you see it |
|---|---|---|---|
| Successor ("before") | `u` must come before `v` | the nodes that wait on it | Textbook algorithms, Kahn's algorithm in this tutorial |
| Predecessor ("depends on") | `u` depends on `v` | the nodes it needs first | Makefiles, package manifests, Python's `graphlib` |
Neither is more correct. They are transposes of each other: reversing every edge converts one into the other. If you sort a predecessor-style graph with an algorithm that expects successor-style edges, you get the exact reverse of a valid order. That bug is easy to miss, because the output looks like a reasonable order.
This tutorial uses the successor convention unless a section says otherwise. A dictionary entry graph[u] = [v, w] means u comes before both v and w.
Storing the Graph in Python
An adjacency list stored as a dictionary of lists fits dependency graphs well. Most dependency graphs are sparse, meaning each task depends on only a few others. An adjacency list uses O(V + E) memory, where V is the number of nodes and E is the number of edges. An adjacency matrix would use O(V²).
Dependencies usually arrive as pairs, so the first job is to build the dictionary from them. Every node must appear as a key, including nodes with no outgoing edges.
def build_graph(pairs):
"""pairs: iterable of (before, after). Returns a successor adjacency list."""
graph = {}
for before, after in pairs:
graph.setdefault(before, []).append(after)
graph.setdefault(after, []) # make sure sink nodes get a key
return graph
pairs = [
("intro", "data_structures"),
("intro", "discrete_math"),
("discrete_math", "algorithms"),
("data_structures", "algorithms"),
]
print(build_graph(pairs))
# {'intro': ['data_structures', 'discrete_math'], 'data_structures': ['algorithms'], 'discrete_math': ['algorithms'], 'algorithms': []}The line graph.setdefault(after, []) is easy to forget. Without it, algorithms would never become a key. Any code that loops over graph to find all nodes would skip it, and any code that runs graph[v] on it would raise KeyError.
Isolated tasks with no dependencies at all never show up in a list of pairs. If your input can contain them, for example a course with no prerequisites that nothing else requires, add them explicitly:
def build_graph_with_nodes(nodes, pairs):
graph = {u: [] for u in nodes}
for before, after in pairs:
graph.setdefault(before, []).append(after)
graph.setdefault(after, [])
return graph
print(build_graph_with_nodes(["intro", "art_history"], [("intro", "algorithms")]))
# {'intro': ['algorithms'], 'art_history': [], 'algorithms': []}Converting Between Conventions
Data often arrives in predecessor form, because people naturally describe what each item needs. A package manifest says "app needs lib and config." To use a successor-style algorithm, invert the mapping:
def invert(deps):
"""deps maps each node to the nodes it depends on.
Returns a successor graph: each node maps to the nodes that depend on it."""
graph = {u: [] for u in deps}
for u, preds in deps.items():
for p in preds:
graph.setdefault(p, []).append(u)
return graph
deps = {
"app": ["lib", "config"],
"lib": ["utils"],
"config": [],
"utils": [],
}
print(invert(deps))
# {'app': [], 'lib': ['app'], 'config': ['app'], 'utils': ['lib']}Inversion takes O(V + E) time, so it never dominates the cost of a sort. Inverting twice gives back the original edges, though the order inside each list may change.
Common Modeling Errors
A wrong graph gives a wrong order without any error message, so it pays to validate input before sorting. These are the problems that show up most often:
- Reversed edges. Explained above. The output is a valid order for the wrong problem.
- Missing keys. A node appears only as an edge target and has no entry of its own. Iteration skips it, or a lookup crashes.
- Self-loops. An edge
u -> usays a task must come before itself. That is almost always a data error, and it makes ordering impossible. - Duplicate edges. Listing
u -> vtwice is harmless for reachability. It breaks any code that counts in-degrees and expects each edge to count once, unless that code also decrements twice. - Inconsistent node names.
"Lib"and"lib", or"utils"and"utils "with a trailing space, become different nodes. The real dependency silently disappears.
A small checker catches the structural problems:
def check_graph(graph):
problems = []
for u, targets in graph.items():
seen = set()
for v in targets:
if v not in graph:
problems.append(f"{v!r} is a target of {u!r} but has no entry")
if v == u:
problems.append(f"self-loop on {u!r}")
if v in seen:
problems.append(f"duplicate edge {u!r} -> {v!r}")
seen.add(v)
return problems
print(check_graph({"a": ["b", "b", "a"], "b": ["c"]}))
# ["duplicate edge 'a' -> 'b'", "self-loop on 'a'", "'c' is a target of 'b' but has no entry"]Self-loops are the shortest kind of cycle. Longer cycles, such as a -> b -> a, are the subject of the next chapter, and later chapters detect them during the sort itself.
What the Graph Leaves Out
A dependency graph records only ordering constraints. It does not record how long tasks take, which resources they use, or whether a dependency is optional. If you need any of that, store it next to the graph, for example as a duration dictionary keyed by node, and keep the edges limited to "must come before." The chapter on dynamic programming on DAGs shows how to combine an order with extra data like this.
Also keep only direct dependencies when you can. If intro -> data_structures -> algorithms already exists, adding intro -> algorithms changes no valid order. It does add edges to process, and it can hide which requirement is the real one.
Exercise
A kitchen recipe says: boil water before cooking pasta; chop garlic before making sauce; cook pasta and make sauce before combining; combine before serving. Using the successor convention, list the edges and the full adjacency dictionary, including every node as a key. Which nodes have in-degree 0?
Show answer
Edges: boilwater -> cookpasta, chopgarlic -> makesauce, cookpasta -> combine, makesauce -> combine, combine -> serve. Dictionary: {"boilwater": ["cookpasta"], "cookpasta": ["combine"], "chopgarlic": ["makesauce"], "makesauce": ["combine"], "combine": ["serve"], "serve": []}. The nodes with in-degree 0 are boilwater and chopgarlic, so either one can be started first.
Exercise
A teammate passes the predecessor-style map {"test": ["build"], "build": ["fetch"], "fetch": []} straight into a function that expects successor-style edges, and it returns ["test", "build", "fetch"]. What went wrong, and what is the correct order?
Show answer
The map says what each task depends on, but the function reads each entry as what comes after it, so every edge is reversed and the output is backwards. Inverting the map gives {"test": [], "build": ["test"], "fetch": ["build"]}, and the correct order is ["fetch", "build", "test"].
Exercise
Why does build_graph call graph.setdefault(after, []) even though it never appends anything to that list?
Show answer
It makes sure every node that appears only as a target, such as a final task with no successors, still gets a key. Without that key, code that loops over the dictionary would miss the node, and code that looks up graph[v] would raise KeyError.