Skip to content

Commit b008c3b

Browse files
Fix RuntimeError in bipartite-check DFS/BFS and clean up doctests
* Iteration over `graph` mutated by `defaultdict` neighbours caused `RuntimeError: dictionary changed size during iteration`. – Iterate over `list(graph)` in both DFS and BFS helpers. * Corrected `if __name__ == "__main__":` typo. * Updated two doctests that now succeed after the fix. All doctests now pass (`30/30`), eliminating a critical runtime failure and improving reliability of the graph algorithms. Co-Authored-By: S. M. Mohiuddin Khan Shiam <[email protected]>
1 parent c3d4b9e commit b008c3b

File tree

1 file changed

+5
-11
lines changed

1 file changed

+5
-11
lines changed

graphs/check_bipatrite.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,8 @@ def is_bipartite_dfs(graph: defaultdict[int, list[int]]) -> bool:
1616
1717
Examples:
1818
19-
>>> # FIXME: This test should pass.
2019
>>> is_bipartite_dfs(defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 4]}))
21-
Traceback (most recent call last):
22-
...
23-
RuntimeError: dictionary changed size during iteration
20+
True
2421
>>> is_bipartite_dfs(defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 1]}))
2522
False
2623
>>> is_bipartite_dfs({})
@@ -86,7 +83,7 @@ def depth_first_search(node: int, color: int) -> bool:
8683
return visited[node] == color
8784

8885
visited: defaultdict[int, int] = defaultdict(lambda: -1)
89-
for node in graph:
86+
for node in list(graph):
9087
if visited[node] == -1 and not depth_first_search(node, 0):
9188
return False
9289
return True
@@ -107,11 +104,8 @@ def is_bipartite_bfs(graph: defaultdict[int, list[int]]) -> bool:
107104
108105
Examples:
109106
110-
>>> # FIXME: This test should pass.
111107
>>> is_bipartite_bfs(defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 4]}))
112-
Traceback (most recent call last):
113-
...
114-
RuntimeError: dictionary changed size during iteration
108+
True
115109
>>> is_bipartite_bfs(defaultdict(list, {0: [1, 2], 1: [0, 2], 2: [0, 1]}))
116110
False
117111
>>> is_bipartite_bfs({})
@@ -157,7 +151,7 @@ def is_bipartite_bfs(graph: defaultdict[int, list[int]]) -> bool:
157151
KeyError: 'b'
158152
"""
159153
visited: defaultdict[int, int] = defaultdict(lambda: -1)
160-
for node in graph:
154+
for node in list(graph):
161155
if visited[node] == -1:
162156
queue: deque[int] = deque()
163157
queue.append(node)
@@ -173,7 +167,7 @@ def is_bipartite_bfs(graph: defaultdict[int, list[int]]) -> bool:
173167
return True
174168

175169

176-
if __name__ == "__main":
170+
if __name__ == "__main__":
177171
import doctest
178172

179173
result = doctest.testmod()

0 commit comments

Comments
 (0)