Sub topic 1
Modeling Dependencies as Directed Graphs
Many problems involve tasks where some steps must happen before others. A library has to compile before the app that uses it. A student takes an intro course before an algorithms course. This tutorial is about ordering such tasks. Before any ordering is possible, you have to describe the dependencies in a form a program can work with. That form is a directed graph.
Prerequisites
This chapter assumes you know:
- Basic Python syntax, including dictionaries and lists
- Graph terms: vertices (nodes), edges, and directed edges
- How an adjacency list stores a graph
- Breadth-first and depth-first search, which come up in later chapters
- Big-O notation, queues, stacks, and recursion
From Dependencies to Edges
Each task becomes a node. Each "must happen before" relation becomes a directed edge. This tutorial uses one convention throughout:
- An edge
u -> vmeans u must come before v.
Under this convention, edges point from a prerequisite to the thing that needs it. That matches the direction of work: you finish u first, then v becomes possible.
Two Ways to Write the Same Graph
Dependency data usually arrives in predecessor form, where each item lists what it requires. Package manifests and course catalogs look like this. Algorithms such as Kahn's algorithm usually want successor form, where each node lists the nodes that depend on it. Converting between them means reversing each relation.
def build_graph(prereqs):
"""prereqs maps each item to the items it requires.
Returns successor form: u -> [v, ...] means u comes before each v."""
graph = {}
for item, needs in prereqs.items():
graph.setdefault(item, [])
for need in needs:
graph.setdefault(need, []).append(item)
return graph
prereqs = {
"algorithms": ["data_structures", "discrete_math"],
"data_structures": ["intro"],
"discrete_math": ["intro"],
"intro": [],
}
print(build_graph(prereqs))
# {'algorithms': [], 'data_structures': ['algorithms'], 'discrete_math': ['algorithms'], 'intro': ['data_structures', 'discrete_math']}Every node appears as a key, including algorithms, which has no outgoing edges. The two setdefault calls make sure of that.
| Form | Key | Value | Typical source |
|---|---|---|---|
| Predecessor | an item | items it requires | manifests, catalogs, `graphlib` |
| Successor | an item | items that require it | input to Kahn's and DFS sorts |
Common Modeling Errors
- Reversed edges. If you store "requires" edges and then run an algorithm that expects "comes before" edges, you get a valid order that runs backwards. Pick one convention and write it in a docstring.
- Missing nodes. A node that appears only as a value, never as a key, can disappear from in-degree counts or loops over
graph. Always register every node as a key. - Duplicate edges. Listing the same dependency twice adds two edges. Some algorithms tolerate this, and others overcount. Deduplicate with a set if your input might repeat entries.
- Hidden circular requirements. If A requires B and B requires A, no valid order exists. Later chapters show how to detect this.
Exercise
A build has three targets: "app" requires "lib" and "config", and "lib" requires "utils". Write the successor-form adjacency list, using u -> v to mean u comes before v, with every node as a key.
Show answer
{"app": [], "lib": ["app"], "config": ["app"], "utils": ["lib"]}. The "app" target has no outgoing edges because nothing depends on it, but it still appears as a key.
Exercise
A teammate's code stores {"algorithms": ["intro"]} and passes it straight to a sort that expects successor form. What goes wrong?
Show answer
The sort reads the entry as "algorithms comes before intro", so the result places algorithms first. The order is valid for the reversed graph and wrong for the real problem. Convert the data with a function like build_graph first.