3

I have an assignment where I have to create a graph using the random library with for loops and also compute the probability whether there is an edge between two vertices. The body of the code is as given below.

How can I construct an graph?

# generate edges in G_rand at random:
for i in range(0,k) :
    for j in range(0,i) : 
        # Add an edge between vertices i and j, with probability edge_probab 
        # ...
1
  • Please don't use all upper-case sentences, not even in your title. It's considered shouting, and is rude. Commented Jul 11, 2020 at 12:04

1 Answer 1

3

Here is a possible solution:

import random
import networkx as nx

edge_probability = 0.3
n_nodes = 10

G = nx.DiGraph()

G.add_nodes_from(range(n_nodes))

for u in G.nodes:
    for v in G.nodes:
        if random.random() < edge_probability:
            G.add_edge(u, v)

Graph generated randomly

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.