Skip to content
Merged
Changes from all commits
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
30 changes: 28 additions & 2 deletions sorts/topological_sort.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
"""Topological Sort."""
"""Topological Sort.

https://en.wikipedia.org/wiki/Topological_sorting
https://en.wikipedia.org/wiki/Directed_acyclic_graph

Note: topological_sort() sorts a directed acyclic graph so topological_sort(2, 1, 3)
should fail.
"""

# a
# / \
Expand All @@ -16,7 +23,26 @@


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', [], [])
['c', 'd', 'e', 'b', 'a']

>>> topological_sort("a", "b", "c")
Traceback (most recent call last):
...
ValueError: visited must be a list

>>> topological_sort("a", [], "c")
Traceback (most recent call last):
...
ValueError: sort must be a list
"""
Comment thread
cclauss marked this conversation as resolved.
if not isinstance(visited, list):
raise ValueError("visited must be a list")
if not isinstance(sort, list):
raise ValueError("sort must be a list")
current = start
# add current to visited
visited.append(current)
Expand Down
Loading