Python/sorts/topological_sort.py
Mehdi ALAOUI 02c0daf9e5 Adding unit tests for sorting functions, and improving readability on some sorting algorithms (#784)
* Adding variable to fade out ambiguity

* More readability on merge sorting algorithm

* Updating merge_sort_fastest description and explaining why

* Adding tests file with imports

* Standardazing filenames and function names

* Adding test cases and test functions

* Adding test loop

* Putting 'user oriented code' inside main condition for having valid imports

* Fixing condition

* Updating tests: adding cases and todo list

* Refactoring first euler problem's first solution
2019-05-25 21:41:24 +08:00

34 lines
1011 B
Python

from __future__ import print_function
# 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
if __name__ == '__main__':
sort = topological_sort('a', [], [])
print(sort)