Skip to content

Instantly share code, notes, and snippets.

@hughdbrown
Last active August 12, 2024 21:04
Show Gist options
  • Save hughdbrown/4486230a9687026f440db19d49d3c365 to your computer and use it in GitHub Desktop.
Save hughdbrown/4486230a9687026f440db19d49d3c365 to your computer and use it in GitHub Desktop.
Try graphlib.TopologicalSort
>>> from graphlib import TopologicalSorter
>>> data = {"A": ["B", "D"], "B": [], "D": [], "C": ["A"]}
>>> ts = TopologicalSorter(data)
>>> for a in ts.static_order():
... print(a)
...
B
D
A
C
>>> data = {"A": ["B", "D"], "B": ["C"], "D": [], "C": ["A"]}
>>> ts = TopologicalSorter(data)
>>> for a in ts.static_order():
... print(a)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/hughbrown/.pyenv/versions/3.12.0/lib/python3.12/graphlib.py", line 244, in static_order
self.prepare()
File "/Users/hughbrown/.pyenv/versions/3.12.0/lib/python3.12/graphlib.py", line 106, in prepare
raise CycleError(f"nodes are in a cycle", cycle)
graphlib.CycleError: ('nodes are in a cycle', ['A', 'C', 'B', 'A'])
# This is a bit unexpected, given that E is not listed as a step that can be fulfilled.
>>> data = {"A": ["B", "D", "E"], "B": [], "D": [], "C": ["A"]}
>>> ts = TopologicalSorter(data)
>>> for a in ts.static_order():
... print(a)
...
B
D
E
A
C
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment