Recursion: how to avoid Python set changed set during iteration RuntimeError

浪子不回头ぞ 提交于 2019-12-03 22:35:28

I think the problem is here:

for color in self.domains[var]:

    if not self._valid(var, color):
        continue

    self.map[var].color = color
    for key in node.neighbors:

        if color in self.domains[key]:
            self.domains[key].remove(color)  # This is potentially bad.

if key == var when self.domains[key].remove(color) is called, you change the size of the set you're currently iterating over. You can avoid this by using

for color in self.domains[var].copy():

Using copy() will allow you to iterate over a copy of the set, while removing items from the original.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!