From c3f84e555c40a9c877b6b2ee1297b3b49666b103 Mon Sep 17 00:00:00 2001 From: Sean Doherty Date: Sat, 16 May 2026 16:54:05 -0500 Subject: [PATCH] Fix topological sort order --- sorts/topological_sort.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/sorts/topological_sort.py b/sorts/topological_sort.py index efce8165fcac..169e3c91104f 100644 --- a/sorts/topological_sort.py +++ b/sorts/topological_sort.py @@ -16,7 +16,12 @@ def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]: - """Perform topological sort on a directed acyclic graph.""" + """ + Perform topological sort on a directed acyclic graph. + + >>> topological_sort("a", [], []) + ['a', 'b', 'e', 'd', 'c'] + """ current = start # add current to visited visited.append(current) @@ -25,8 +30,8 @@ def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[st # 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 neighbors visited add current before its neighbors in sort + sort.insert(0, current) # if all vertices haven't been visited select a new one to visit if len(visited) != len(vertices): for vertice in vertices: