From b008c3b700f11387db0d14b2850832b52ab40db8 Mon Sep 17 00:00:00 2001 From: Odio Marcelino Date: Sun, 29 Jun 2025 20:10:14 +0600 Subject: [PATCH] Fix `RuntimeError` in bipartite-check DFS/BFS and clean up doctests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 <147746955+mohiuddin-khan-shiam@users.noreply.github.com> --- graphs/check_bipatrite.py | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/graphs/check_bipatrite.py b/graphs/check_bipatrite.py index 213f3f9480b5..c6fbca29bb28 100644 --- a/graphs/check_bipatrite.py +++ b/graphs/check_bipatrite.py @@ -16,11 +16,8 @@ def is_bipartite_dfs(graph: defaultdict[int, list[int]]) -> bool: Examples: - >>> # FIXME: This test should pass. >>> is_bipartite_dfs(defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 4]})) - Traceback (most recent call last): - ... - RuntimeError: dictionary changed size during iteration + True >>> is_bipartite_dfs(defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 1]})) False >>> is_bipartite_dfs({}) @@ -86,7 +83,7 @@ def depth_first_search(node: int, color: int) -> bool: return visited[node] == color visited: defaultdict[int, int] = defaultdict(lambda: -1) - for node in graph: + for node in list(graph): if visited[node] == -1 and not depth_first_search(node, 0): return False return True @@ -107,11 +104,8 @@ def is_bipartite_bfs(graph: defaultdict[int, list[int]]) -> bool: Examples: - >>> # FIXME: This test should pass. >>> is_bipartite_bfs(defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 4]})) - Traceback (most recent call last): - ... - RuntimeError: dictionary changed size during iteration + True >>> is_bipartite_bfs(defaultdict(list, {0: [1, 2], 1: [0, 2], 2: [0, 1]})) False >>> is_bipartite_bfs({}) @@ -157,7 +151,7 @@ def is_bipartite_bfs(graph: defaultdict[int, list[int]]) -> bool: KeyError: 'b' """ visited: defaultdict[int, int] = defaultdict(lambda: -1) - for node in graph: + for node in list(graph): if visited[node] == -1: queue: deque[int] = deque() queue.append(node) @@ -173,7 +167,7 @@ def is_bipartite_bfs(graph: defaultdict[int, list[int]]) -> bool: return True -if __name__ == "__main": +if __name__ == "__main__": import doctest result = doctest.testmod()