Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sage code for generating random weighted undirected graph
## Generates a random weighted undirected graph.
## n = number of nodes
## p = probability that two nodes are adjacent; must be between 0 and 1.
## lower_weight and upper_weight = lower and upper edge weights, respectively. If left out, the defaults are 1 and 100.
##
## Examples of usage:
## g = random_weighted_graph(20, 0.5) <-- Uses default lower and upper weights of 1 and 100.
## h = random_weighted_graph(10, 0.35, 5, 50) <-- Weights will be integers between 5 and 50.
## g.show(edge_labels = True) <-- Include the argument to display the weights
## h.show() <-- leave the argument out to hide the weights
def random_weighted_graph(n, p, lower_weight = 1, upper_weight = 100):
import random
g = graphs.RandomGNP(n,p)
m = g.num_edges()
weights = [random.randint(lower_weight, upper_weight) for r in xrange(m)]
uw_edges = g.edges()
# Create weighted graph edge list
w_edges = [(uw_edges[i][0], uw_edges[i][1], weights[i]) for i in xrange(m)]
return Graph(w_edges, weighted = True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.