Last active
August 12, 2024 21:04
-
-
Save hughdbrown/4486230a9687026f440db19d49d3c365 to your computer and use it in GitHub Desktop.
Try graphlib.TopologicalSort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> 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