Add the topological sort sample and the solution
This commit is contained in:
21
notes-and-examples/2026.08.27/topological_sort.py
Normal file
21
notes-and-examples/2026.08.27/topological_sort.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from collections import deque
|
||||
# double-ended queue, this may be helpful
|
||||
# see the docs: https://docs.python.org/3/library/collections.html#collections.deque
|
||||
|
||||
classes = {
|
||||
'CPSC 230': {'CPSC 231'},
|
||||
'CPSC 231': {'CPSC 350', 'CPSC 330'},
|
||||
'CPSC 350': {'CPSC 380', 'CPSC 408', 'CPSC 406'},
|
||||
'CPSC 330': {'CPSC 351'},
|
||||
'CPSC 351': set(),
|
||||
'ENGR 101': set(),
|
||||
'CPSC 380': set(),
|
||||
'CPSC 406': set(),
|
||||
'CPSC 408': set()
|
||||
}
|
||||
|
||||
def topological_sort(adjacency_list: dict[str, set[str]]):
|
||||
# return the sorted ordering
|
||||
return []
|
||||
|
||||
print(topological_sort(classes))
|
||||
47
notes-and-examples/2026.08.27/topological_sort_solution.py
Normal file
47
notes-and-examples/2026.08.27/topological_sort_solution.py
Normal file
@@ -0,0 +1,47 @@
|
||||
from collections import deque
|
||||
|
||||
# This is a solution which uses DFS to trace the paths; there
|
||||
# are other solutions as well
|
||||
|
||||
classes = {
|
||||
'CPSC 230': {'CPSC 231'},
|
||||
'CPSC 231': {'CPSC 350', 'CPSC 330'},
|
||||
'CPSC 350': {'CPSC 380', 'CPSC 408', 'CPSC 406'},
|
||||
'CPSC 330': {'CPSC 351'},
|
||||
'CPSC 351': set(),
|
||||
'ENGR 101': set(),
|
||||
'CPSC 380': set(),
|
||||
'CPSC 406': set(),
|
||||
'CPSC 408': set()
|
||||
}
|
||||
|
||||
|
||||
def topological_sort(adjacency_list: dict[str, set[str]]):
|
||||
result = deque()
|
||||
visited = set()
|
||||
|
||||
def dfs(current: str, visited_in_traversal=None):
|
||||
if visited_in_traversal is None:
|
||||
visited_in_traversal = set()
|
||||
if current in visited:
|
||||
return
|
||||
if current in visited_in_traversal:
|
||||
raise ValueError("Graph has a cycle")
|
||||
|
||||
visited_in_traversal.add(current)
|
||||
|
||||
for neighbor in adjacency_list[current]:
|
||||
dfs(neighbor, visited_in_traversal)
|
||||
|
||||
# to trace the reverse path, use .append
|
||||
result.appendleft(current)
|
||||
visited.add(current)
|
||||
|
||||
for node in adjacency_list.keys():
|
||||
if node not in visited:
|
||||
dfs(node)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
print(topological_sort(classes))
|
||||
Reference in New Issue
Block a user