Skip to content

Instantly share code, notes, and snippets.

@RobertTalbert
Last active October 18, 2022 14:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobertTalbert/9f0879e5ed4b4297fc5f to your computer and use it in GitHub Desktop.
Save RobertTalbert/9f0879e5ed4b4297fc5f to your computer and use it in GitHub Desktop.
Python/Sage code for generating random weighted graphs
'''
Generates a random weighted graph in Sage.
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 random_weighted_graph(n, p, lower_weight, upper_weight):
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)
@Neestech
Copy link

Hi
I used of this code in my project bud in 12 line 'g = graphs.RandomGNP(n,p)' I see an error : name 'RandomGNP' is not defined. Can you help me?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment