In: Computer Science
Write a Python/NetworkX function add_weights(G1, G1), where G1 and G1 are intended to be graphs with exactly the same edges and such that each edge has either no attribute or a single attribute, ‘weight’, with a numerical value. It returns a graph, say, G3, that has the same edges as G1 and G2. Each edge e of G3 has a single attribute, ‘weight’, whose value is the sum of the ‘weight’ attributes of e in G1 and of e in G2 if ein G1 and e in G2 both have attribute ‘weight’. Otherwise, if e in one of G1 or G2 has attribute ‘weight’, then the value of ‘weight’ in G3 is the value of that ‘weight’ attribute. Otherwise (i.e., neither e in G1 nor e in G2 has attribute ‘weight’), the value of attribute ‘weight’ in e in G3is 0. This function returns G3.
Note that, where G is a graph with an edge (u, v), G[u][v] counts as False in a position expecting a Boolean value if the edge (u, v)in G has no edge attributes. This is useful in this problem since an edge either has a single attribute, ‘weight’, or has no attribute.
The following is test code, followed by its output.
if __name__ == "__main__" :
Ga = nx.Graph()
Ga.add_edges_from([(0, 1, {'weight': 2}), (1, 2, {'weight': 4}),
(2, 3), (3, 1, {'weight': 2}), (0, 3)])
Gb = nx.Graph()
Gb.add_edges_from([(0, 1, {'weight': 3}), (1, 2, {'weight': 5}),
(2, 3, {'weight':3}), (3, 1), (0, 3)])
for u, v, attr in add_weights(Ga, Gb).edges(data=True):
wGa = Ga[u][v]['weight'] if Ga[u][v] else None
wGb = Gb[u][v]['weight'] if Gb[u][v] else None
print("Edge ({}, {}): {} + {} = {}".format(u, v, wGa, wGb,
attr['weight']))
Output:
Edge (0, 1): 2 + 3 = 5
Edge (0, 3): None + None = 0
Edge (1, 2): 4 + 5 = 9
Edge (1, 3): 2 + None = 2
Edge (3, 2): None + 3 = 3
Below is the function in python/networkx
def add_weights(G1,G2):
G3 = nx.Graph()
edgelist = []
for u,v in G1.edges():
sum = 0
if G1[u][v]:
sum += G1[u][v]['weight']
if G2[u][v]:
sum += G2[u][v]['weight']
edgelist.append(u,v,{'weight':sum})
G3.add_edges_from(edgelist)
return G3
After including this function, when you run the complete code given in question , the following is the output
Output
Edge (0, 1): 2 + 3 = 5
Edge (0, 3): None + None = 0
Edge (1, 2): 4 + 5 = 9
Edge (1, 3): 2 + None = 2
Edge (3, 2): None + 3 = 3
Below is the code screenshot for indentation reference. Please let me know if you have any questions/doubts etc. I would help further. Thanks