diff --git a/sorts/topological_sort.py b/sorts/topological_sort.py index efce8165fcac..4c70b436e0ec 100644 --- a/sorts/topological_sort.py +++ b/sorts/topological_sort.py @@ -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 # / \ @@ -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 + """ + 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)