I'm trying to create a sort of residual network from a given network, for that I'm first creating the reverse edges that doesn't exist in the graph, but I keep getting the message
RuntimeError: dictionary changed size during iteration
First I was obviously iterating over an object that was being modified during the loop:
def Gf(Graph): #residual graph
for u in Graph:
for v in Graph[u]:
if u in Graph[v]:
pass
else:
Graph[v][u]=0 #create the edge with capacity 0
return Graph
Where the graph Graph is an object of the form (I'm new to python so I don't know if this is the best way to do it)
defaultdict(lambda: defaultdict(lambda:0))
with values Graph[u][v] set to capacity of the edge u,v.
So I created a copy of Graph and tried to iterate over that object
def Gf(Graph): #residual graph
Graph_Copy=Graph.copy()
for u in Graph_Copy:
for v in Graph_Copy[u]:
if u in Graph_Copy[v]:
pass
else:
Graph[v][u]=0
return Graph
But that didn't work. I tried some other ways (create a deepcopy; create an empty object Graph_Copy, iterate over Graph and then set adequate values to Graph_Copy) but no luck so far. What I'm doing wrong?