From 16b0d62f2843b51f3bd983ea574b6ba553e391ae Mon Sep 17 00:00:00 2001 From: Zach Wild Date: Wed, 21 Jun 2017 19:11:31 -0400 Subject: [PATCH] Add topological_sort.py --- sorts/topological_sort.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 sorts/topological_sort.py diff --git a/sorts/topological_sort.py b/sorts/topological_sort.py new file mode 100644 index 000000000..5de1cc2b7 --- /dev/null +++ b/sorts/topological_sort.py @@ -0,0 +1,32 @@ +# a +# / \ +# b c +# / \ +# d e +edges = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []} +vertices = ['a', 'b', 'c', 'd', 'e'] + + +def topological_sort(start, visited, sort): + """Perform topolical sort on a directed acyclic graph.""" + current = start + # add current to visited + visited.append(current) + neighbors = edges[current] + for neighbor in neighbors: + # if neighbor not in visited, visit + if neighbor not in visited: + sort = topological_sort(neighbor, visited, sort) + # if all neighbors visited add current to sort + sort.append(current) + # if all vertices haven't been visited select a new one to visit + if len(visited) != len(vertices): + for vertice in vertices: + if vertice not in visited: + sort = topological_sort(vertice, visited, sort) + # return sort + return sort + + +sort = topological_sort('a', [], []) +print(sort)