how to bypass 'dictionary changed size during iteration'

血红的双手。 提交于 2019-12-12 01:24:42

问题


I'm writing a heuristic function for a problem that can be presented by a table (a tuple of tuples) and I'm starting with some random cells in my table which I give a 0 value, then adding 1 to its neighbors and so on - this value is later can be shown in a dictionary - where the key is the cell's coords and the value is its value. everytime I get into a new cell, I save it into my dic.

The problem - for this BFS-ish method which I made, I need some kind of a dynamic sized dictionary. There are some initial keys when I start iterating, then more are added when the code runs - and the code needs to check those new cells too. While I thought python will be able to handle this, I got a runtime error that says "RuntimeError: dictionary changed size during iteration"

    visitedCells = dict()
    for row in range(len(node.state)):
        for cell in range(len(node.state[0])):
            if STATEMENT:
                visitedCells[row, cell] = 0

    for cell, val in visitedCells.items():
        row = cell[0]
        col = cell[1]

        if STATEMENT:
            visitedCells[row + 1, col] = val + 1
        if STATEMENT:
            visitedCells[row - 1, col] = val + 1
        if STATEMENT:
            visitedCells[row, col + 1] = val + 1
        if STATEMENT:
            visitedCells[row, col - 1] = val + 1

I expect it to actually change size and continue during iteration. Is there any way to do this?


回答1:


You can maintain a queue for the cells to visit and a separate dictionary which indicates the state of each cell:

queue = list(visitedCells.items())
while queue:
    row, col = queue.pop(0)

    if STATEMENT:
        visitedCells[row + 1, col] = val + 1
        queue.append((row + 1, col))
    ...


来源:https://stackoverflow.com/questions/54156227/how-to-bypass-dictionary-changed-size-during-iteration

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