Python, RuntimeError: dictionary changed size during iteration -
i'm trying create sort of residual network given network, i'm first creating reverse edges doesn't exist in graph, keep getting message
runtimeerror: dictionary changed size during iteration
first iterating on object being modified during loop:
def gf(graph): #residual graph u in graph: v in graph[u]: if u in graph[v]: pass else: graph[v][u]=0 #create edge capacity 0 return graph
where graph graph object of form (i'm new python don't know if best way it)
defaultdict(lambda: defaultdict(lambda:0))
with values graph[u][v] set capacity of edge u,v.
so created copy of graph , tried iterate on object
def gf(graph): #residual graph graph_copy=graph.copy() u in graph_copy: v in graph_copy[u]: if u in graph_copy[v]: pass else: graph[v][u]=0 return graph
but didn't work. tried other ways (create deepcopy; create empty object graph_copy, iterate on graph , set adequate values graph_copy) no luck far. i'm doing wrong?
honestly, don't know causing exception. know, however, is bad idea use nested dictionaries represent graphs. harder iterate over, have discovered, , have more overhead. instead, should use nested list.
if understand current data structure correctly, can represented followed:
graph = { u0: {v0: 0, v1: 0, ... }, u1: {v0: 0, v1: 0, ... }, ... } # curly brackets denote dictionaries
the better representation be:
graph = [ [0, 0, 0, ...], [0, 0, 0, ...], ... ] # brackets denote lists
this default way encode distance matrix (http://en.wikipedia.org/wiki/distance_matrix) representation of graph. if have coded in other languages c/c++, equivalent of 2-dimensional array.
assuming u
& v
labels graph vertices, can represented numerical values, i.e. 0 1st node, 1 2nd, , on. accessing value of edge u-v
simple doing graph[u][v]
.
now, let's assume have changed code graph g has n vertices represented nested list/2d array of size nxn, function can rewritten followed:
def gf(g): # python style guideline recommends lower case variable & function names vertices_count = len(g) # size of original graph gf = [] # initialize new redidual graph u in range(vertices_count): gf.append([0]*vertices_count) # initialize edges v in range(vertices_count): if g[u][v] > 0: # here if value of edge u-v more zero, e.g. gf[u][v] = formula else: # here if value of edge u-v zero,, e.g. gf[u][v] = 0 return gf
Comments
Post a Comment