Random Graph Generation with Additional Edge

  • Share this:

Code introduction


This function generates a random graph with a specified number of nodes and edges, and randomly adds an edge between two nodes in the graph.


Technology Stack : NetworkX

Code Type : Function

Code Difficulty : Intermediate


                
                    
import networkx as nx
import random

def generate_random_graph(num_nodes, num_edges):
    """
    Generates a random graph with a specified number of nodes and edges.
    """
    # Generate a random graph
    G = nx.erdos_renyi_graph(num_nodes, num_edges/num_nodes)
    
    # Randomly select two nodes and add an edge between them
    node1 = random.choice(list(G.nodes()))
    node2 = random.choice(list(G.nodes()))
    G.add_edge(node1, node2)
    
    return G

# Code Information                
              
Tags: