Skip to content

Commit 58f7679

Browse files
author
Kcstring
committed
refactor(topological_sort): apply review follow-ups
1 parent 504c6a6 commit 58f7679

1 file changed

Lines changed: 10 additions & 6 deletions

File tree

sorts/topological_sort.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@ def _visit(
2121
post_order: list[str],
2222
graph: dict[str, list[str]],
2323
) -> None:
24-
"""Visit all descendants of the current vertex using DFS."""
24+
"""Visit descendants of ``current``.
25+
26+
Appends to ``visited`` and ``post_order`` in place.
27+
"""
2528
visited.append(current)
2629
for neighbor in graph[current]:
2730
if neighbor not in visited:
@@ -32,7 +35,7 @@ def _visit(
3235
def topological_sort(
3336
start: str,
3437
visited: list[str],
35-
sort: list[str],
38+
order: list[str],
3639
graph: dict[str, list[str]] | None = None,
3740
vertices_list: list[str] | None = None,
3841
) -> list[str]:
@@ -52,13 +55,14 @@ def topological_sort(
5255
if vertices_list is None:
5356
vertices_list = list(graph)
5457

55-
_visit(start, visited, sort, graph)
58+
_visit(start, visited, order, graph)
5659
if len(visited) != len(vertices_list):
5760
for vertice in vertices_list:
5861
if vertice not in visited:
59-
_visit(vertice, visited, sort, graph)
60-
sort.reverse()
61-
return sort
62+
_visit(vertice, visited, order, graph)
63+
# DFS post-order is reverse topological order, so reverse once at the end.
64+
order.reverse()
65+
return order
6266

6367

6468
if __name__ == "__main__":

0 commit comments

Comments
 (0)