Graph generation using Networkx

Question:

I would like to generate undirected graphs without self-loops using networkx library using the following idea: in the beginning we have two nodes and one edge that is connecting them. Then on the next iterations we create new node and connect it with two edges to random chosen nodes of the graph. So then next iteration will be 3 nodes and three edges (circle), then 4 nodes and 5 edges, 5 nodes and 7 edges, etc.

Here is my approach:

import random
import networkx as nx
    
def generateGraph(n):
    G = nx.Graph()
    G.add_node(0)
    G.add_node(1)
    G.add_edge(0, 1)
    nodes = []
    
    while G.number_of_nodes() < n:
        new_node = G.number_of_nodes()
        new_edge = G.number_of_edges()
        G.add_node(new_node)
        destination = random.choice(new_node)
        nodes.append(destination)
        G.add_edge(new_node, new_edge)
        G.add_edge(node, new_edge)
    return G

What am I missing here and how can I change my approach? The problem that there are only n nodes and n+1 edges using this model but it should be n nodes and +2 edges(after 5 nodes). Thank you

Asked By: Keithx

||

Answers:

Probably, this should follow your algorithm

def generate_graph(n):
    G = nx.Graph([ (0, 1) ])  # put list of edges

    for n in range(2, n):
        # take two nodes randomly
        nodes_to_take = random.sample(list(G.nodes), 2)
        G.add_edges_from([   # connect new node 'n' with two chosen nodes from graph
            (n, nodes_to_take[0]), (n, nodes_to_take[1])
        ])

    return G

Result:

gr = generate_graph(7)
nx.draw_networkx(gr)

enter image description here

Answered By: glebcom
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.