Skip to content

Fix RuntimeError in bipartite-check DFS/BFS and clean up doctests #12814

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 5 additions & 11 deletions graphs/check_bipatrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -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({})
Expand Down Expand Up @@ -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
Expand All @@ -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({})
Expand Down Expand Up @@ -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)
Expand All @@ -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()
Expand Down
Loading