Sub topic 1
Modeling Dependencies as Directed Graphs
Prerequisites
This chapter assumes you know basic Python syntax and graph terms such as vertex, edge, and directed edge. It also assumes you can read an adjacency list, which is a dictionary that maps each node to the nodes it points to.
Dependencies as Edges
Many tasks must happen in a fixed order. A course needs its prerequisites first, and a program needs its libraries compiled first. You can model these rules as a directed graph. Each task is a node. An edge u -> v means "u must come before v."
A common error is reversing the edge direction, so that u -> v means "u depends on v." Either convention works if you use it consistently. Mixing the two produces orders that come out backwards.
Directed Acyclic Graphs
A directed cycle is a path that follows edges and returns to its starting node, such as a -> b -> c -> a. A directed acyclic graph (DAG) is a directed graph with no directed cycles. Dependency graphs should be DAGs, because a cycle means every task in it waits on another task in the same cycle.
What a Topological Order Is
A topological order is a list of all the nodes in which, for every edge u -> v, u appears before v. The function below checks a candidate order:
def is_topological_order(graph, order):
pos = {u: i for i, u in enumerate(order)}
if len(pos) != len(order) or set(pos) != set(graph):
return False # duplicates, missing nodes, or extra nodes
return all(pos[u] < pos[v] for u in graph for v in graph[u])
courses = {
"intro": ["data_structures", "discrete_math"],
"discrete_math": ["algorithms"],
"data_structures": ["algorithms"],
"algorithms": [],
}
print(is_topological_order(courses, ["intro", "discrete_math", "data_structures", "algorithms"])) # True
print(is_topological_order(courses, ["intro", "algorithms", "discrete_math", "data_structures"])) # FalseWhy Only DAGs Have Topological Orders
A directed graph has a topological order if and only if it is a DAG.
- A cycle rules out any order. Take a cycle
v1 -> v2 -> ... -> vk -> v1. A valid order would need v1 before v2, v2 before v3, and so on up to vk before v1. Together these say v1 comes before itself, which is impossible. - Every DAG has an order. A finite DAG always has at least one node with no incoming edges. If no such node existed, you could keep stepping backward along incoming edges forever. With finitely many nodes, that walk would revisit a node and form a cycle. Put a node with no incoming edges first, delete it, and repeat. The graph that remains is still a DAG, so the process continues until every node is placed.
Exercise
For the graph {"a": ["b"], "b": ["c"], "c": ["a"]}, does istopologicalorder return True for any ordering of a, b, c? Why?
Show answer
No. The edges form the cycle a -> b -> c -> a, so any order breaks at least one edge, and the function returns False for every permutation.