Last active
October 18, 2022 14:49
-
-
Save RobertTalbert/9f0879e5ed4b4297fc5f to your computer and use it in GitHub Desktop.
Python/Sage code for generating random weighted graphs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?