Created
March 19, 2018 20:11
-
-
Save msoedov/ec509f18f90bebf5e9be1dcea1f65051 to your computer and use it in GitHub Desktop.
sort_direct_acyclic_graph
This file contains hidden or 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
import collections | |
def topological_sort(edge_list): | |
graph = collections.defaultdict(set) | |
for node, child in edge_list: | |
graph[node].add(child) | |
nodes = set(graph) | |
visited = set() | |
ordered = set() | |
order = [] | |
def dfs(node): | |
for ch in graph[node]: | |
if ch in ordered: | |
continue | |
if ch in visited: | |
raise ValueError('Invalid') | |
visited.add(ch) | |
nodes.discard(ch) | |
dfs(ch) | |
ordered.add(node) | |
order.append(node) | |
while nodes: | |
dfs(nodes.pop()) | |
return order | |
u = [ | |
['a', 'b'], # a -> b, etc. | |
['a', 'c'], | |
['b', 'e'], | |
['c', 'd'], | |
['b', 'd'], | |
['e', 'f'], | |
['c', 'f'], | |
] | |
assert topological_sort(u) == ['a', 'c', 'b', 'e', 'd', 'f'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment