Generating a Random Graph

  • Share this:

Code introduction


Create a random graph with specified number of vertices and edges.


Technology Stack : Graph-tool, NumPy

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def create_random_graph(num_vertices, num_edges):
    from graph_tool import Graph
    import numpy as np
    
    # Create a graph with specified number of vertices
    g = Graph(directed=False)
    g.add_vertex(num_vertices)
    
    # Add random edges to the graph
    for _ in range(num_edges):
        v1 = np.random.randint(0, num_vertices)
        v2 = np.random.randint(0, num_vertices)
        g.add_edge(v1, v2)
    
    return g

# Code Information