Skip to content

Commit c3f84e5

Browse files
Fix topological sort order
1 parent 791deb4 commit c3f84e5

1 file changed

Lines changed: 8 additions & 3 deletions

File tree

sorts/topological_sort.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,12 @@
1616

1717

1818
def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]:
19-
"""Perform topological sort on a directed acyclic graph."""
19+
"""
20+
Perform topological sort on a directed acyclic graph.
21+
22+
>>> topological_sort("a", [], [])
23+
['a', 'b', 'e', 'd', 'c']
24+
"""
2025
current = start
2126
# add current to visited
2227
visited.append(current)
@@ -25,8 +30,8 @@ def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[st
2530
# if neighbor not in visited, visit
2631
if neighbor not in visited:
2732
sort = topological_sort(neighbor, visited, sort)
28-
# if all neighbors visited add current to sort
29-
sort.append(current)
33+
# if all neighbors visited add current before its neighbors in sort
34+
sort.insert(0, current)
3035
# if all vertices haven't been visited select a new one to visit
3136
if len(visited) != len(vertices):
3237
for vertice in vertices:

0 commit comments

Comments
 (0)