How to create a random networkx graph with random weights

I am trying to create a random network diagram with each edge having a random weight (representing length).

I am currently using the gnm_random_graph function from a set of networkx graph generators :

 g=nx.gnm_random_graph(5,5) 

However, I am trying to add random weights. My attempt is based on the answers to this question .

 for u,v,w in in g.edges(data=True): w = np.random.randint(0,10) 

I am doing this so that I can learn and (hopefully) understand the networkx library.

My question has two parts:

1. What is the best way to generate a simple network diagram? For instance:

2. What is the best way to add weights to an existing networkx schedule?

+6
source share
1 answer

Just question 2 (Q1 is very context sensitive)

you can use

 import random #code creating G here for (u, v) in G.edges(): G.edge[u][v]['weight'] = random.randint(0,10) 

or use

 for (u,v,w) in G.edges(data=True): w['weight'] = random.randint(0,10) 

The variable w is a dictionary whose keys are all different edge attributes.

+4
source

All Articles