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
Prev Previous commit
Next Next commit
Fixed
  • Loading branch information
VarshiniShreeV committed Oct 27, 2024
commit 6a6876fc1048b315e9f8ae0859d1a931cf390563
38 changes: 34 additions & 4 deletions sorts/topological_sort.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,52 @@
"""Topological Sort on Directed Acyclic Graph(DAG)"""

# a
# / \
# b c
# / \
# d e

edges: dict[str, list[str]] = {
"a": ["c", "b"],
"b": ["d", "e"],
"c": [],
"d": [],
"e": [],
}

vertices: list[str] = ["a", "b", "c", "d", "e"]

"""Perform topological sort on a directed acyclic graph(DAG) starting from the specified node"""

Check failure on line 19 in sorts/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/topological_sort.py:19:89: E501 Line too long (96 > 88)
def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]:
visited.append(start)
current = start
for neighbor in edges[start]:
# Mark the current node as visited
visited.append(current)
# List of all neighbours of current node
neighbors = edges[current]

# Traverse all neighbours of the current node
for neighbor in neighbors:
# Recursively visit each unvisited neighbour
if neighbor not in visited:
topological_sort(neighbor, visited, sort)
sort = topological_sort(neighbor, visited, sort)

# After visiting all neigbours, add the current node to the sorted list
sort.append(current)

# If there are some nodes that were not visited (disconnected components)
if len(visited) != len(vertices):
for vertice in vertices:
if vertice not in visited:
sort = topological_sort(vertice, visited, sort)

# Return sorted list
return sort

if __name__ == "__main__":
# Topological Sorting from node "a" (Returns the order in bottom up approach)
sort = topological_sort("a", [], [])
sort.reverse() #Top down approach

# Reversing the list to get the correct topological order (Top down approach)
sort.reverse()

Check failure on line 50 in sorts/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W291)

sorts/topological_sort.py:50:19: W291 Trailing whitespace

print(sort)

Check failure on line 52 in sorts/topological_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W292)

sorts/topological_sort.py:52:16: W292 No newline at end of file
Loading