Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Generates a random weighted graph.
n = Number of nodes.
p = Probability of two nodes being connected. Must be between 0 and 1.
Weights on the edges are randomly generated integers situated between lower_weight and upper_weight.
Example: random_weighted_graph(6, 0.25, 10, 20) creates a weighted graph with 6 nodes, a 1/4 probability
of two nodes being connected, and weights on the edges randomly selected between 10 and 20.
def gnp_random_weighted_graph(n,p,wlow,whigh):
import random
G = nx.random_graphs.gnp_random_graph(n,p)
m = G.number_of_edges()
weights = [random.randint(wlow,whigh) for r in range(m)]
unweighted_edges = G.edges()
weighted_edges = [(unweighted_edges[i][0], unweighted_edges[i][1], {'weight':weights[i]}) for i in range(m)]
return nx.Graph(weighted_edges)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment