from collections import defaultdict
deftopo_sort(graph): in_degree = {node: 0for node in graph}
for node in graph:
for neighbor in graph[node]:
in_degree[neighbor] += 1 queue = [node for node in in_degree if in_degree[node] == 0]
result = []
while queue:
node = queue.pop(0)
result.append(node)
for neighbor in graph[node]:
in_degree[neighbor] -= 1if in_degree[neighbor] == 0:
queue.append(neighbor)
iflen(result) == len(graph):
return result
else:
return [] # Cycle detected in the graph# Example usagegraph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D'],
'D': []
}
print(topo_sort(graph))