Skip to content

Commit 278619a

Browse files
committed
Rename variables, remove print
1 parent 899a8f2 commit 278619a

File tree

1 file changed

+7
-10
lines changed

1 file changed

+7
-10
lines changed

graphs/kahns_algorithm_topo.py

+7-10
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,12 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:
2121
2222
>>> graph_with_cycle = {0: [1], 1: [2], 2: [0]}
2323
>>> topological_sort(graph_with_cycle)
24-
Cycle exists
2524
"""
2625

27-
# Initialize indegree array
2826
indegree = [0] * len(graph)
2927
queue = []
30-
topo = [] # topological order of vertices
31-
cnt = 0 # no. of vertices processed
28+
topo_order = []
29+
processed_vertices_count = 0
3230

3331
# Calculate the indegree of each vertex
3432
for values in graph.values():
@@ -43,19 +41,18 @@ def topological_sort(graph: dict[int, list[int]]) -> list[int] | None:
4341
# Perform BFS
4442
while queue:
4543
vertex = queue.pop(0)
46-
cnt += 1
47-
topo.append(vertex)
44+
processed_vertices_count += 1
45+
topo_order.append(vertex)
4846

4947
# Traverse neighbors
5048
for neighbor in graph[vertex]:
5149
indegree[neighbor] -= 1
5250
if indegree[neighbor] == 0:
5351
queue.append(neighbor)
5452

55-
if cnt != len(graph):
56-
print("Cycle exists")
57-
return None # no topological ordering exists
58-
return topo # valid topological ordering
53+
if processed_vertices_count != len(graph):
54+
return None # no topological ordering exists due to cycle
55+
return topo_order # valid topological ordering
5956

6057

6158
if __name__ == "__main__":

0 commit comments

Comments
 (0)