mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-18 09:10:16 +00:00
bd4017928e
* Added Whitespace and Docstring I modified the file to make Pylint happier and make the code more readable. * Beautified Code and Added Docstring I modified the file to make Pylint happier and make the code more readable. * Added DOCSTRINGS, Wikipedia link, and whitespace I added DOCSTRINGS and whitespace to make the code more readable and understandable. * Improved Formatting * Wrapped comments * Fixed spelling error for `movement` variable * Added DOCSTRINGs * Improved Formatting * Corrected whitespace to improve readability. * Added docstrings. * Made comments fit inside an 80 column layout.
37 lines
1.0 KiB
Python
37 lines
1.0 KiB
Python
"""Topological Sort."""
|
|
|
|
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)
|