Skip to content

Fixes #12192 #12292

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fixed
  • Loading branch information
VarshiniShreeV committed Oct 26, 2024
commit 3ceccfb59cec84f5871ad5efd31a3e43d42867b7
27 changes: 4 additions & 23 deletions sorts/topological_sort.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
"""Topological Sort."""

# a
# / \
# b c
# / \
# d e
edges: dict[str, list[str]] = {
"a": ["c", "b"],
"b": ["d", "e"],
Expand All @@ -14,28 +7,16 @@
}
vertices: list[str] = ["a", "b", "c", "d", "e"]


def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]:
"""Perform topological sort on a directed acyclic graph."""
visited.append(start)
current = start
# add current to visited
visited.append(current)
neighbors = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
for neighbor in edges[start]:
if neighbor not in visited:
sort = topological_sort(neighbor, visited, sort)
# if all neighbors visited add current to sort
topological_sort(neighbor, visited, 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", [], [])
sort.reverse() #Top down approach
print(sort)