Order Dependencies and Detect Cycles
Core idea
A topological order places every prerequisite before its dependent in a directed acyclic graph (DAG). The order need not be unique. graphlib.TopologicalSorter accepts a mapping from each task to its predecessors (not successors). A directed cycle prevents any complete valid order.
from graphlib import TopologicalSorterorder = list(TopologicalSorter({'ship': {'pack'}, 'pack': {'check'}}).static_order())print(order)Even the predecessor-only vertex check is included.
Detect a cycle
from graphlib import TopologicalSorter, CycleErrortry: list(TopologicalSorter({'A': {'B'}, 'B': {'A'}}).static_order())except CycleError: print('cycle')Neither task can be first.
Common mistake
Do not assume a unique order among unrelated tasks. Validate every dependency instead of relying on one exact sequence.
Practice
Add an independent task to the first graph. Check positions for each prerequisite rather than one fixed order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Topological sort
Check your understanding of topological sort.
What is printed?
from graphlib import TopologicalSorterprint(list(TopologicalSorter({'b':{'a'}}).static_order()))What is printed?
order=['a','c','b']print(order.index('a')<order.index('b'))What graph allows a complete topological order?
What are mapping values in TopologicalSorter?