问题
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