Skip to content
Advertisement

“RuntimeError: dictionary changed size during iteration” but it’s not changed in the loop

I’m solving this LeetCode problem and here’s my code:

JavaScript

The line for c in adjacent throws “RuntimeError: dictionary changed size during iteration”, which I don’t understand. I’m not modifying adjacent in dfs(), am I?

Advertisement

Answer

The main Problem is when dfs method is called it uses this line

JavaScript

This just returns the associated value if it exists in defaultdict, if it doesn’t exist in it, it creates and adds a key if you try to access key that doesn’t exist.

Potential line that triggers accessing adjacent defaultdict without knowing whether it exist or not is

JavaScript

neighbor might be or might not be in adjacent defaultdict this causes defaultdict to change. You might check if it exists if not u might want to skip.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement