Skip to content
{{ message }}

Instantly share code, notes, and snippets.

# RobertTalbert/gnp_random_weighted_graph.py

Created Oct 14, 2016
 ''' 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], unweighted_edges[i], {'weight':weights[i]}) for i in range(m)] return nx.Graph(weighted_edges)
to join this conversation on GitHub. Already have an account? Sign in to comment