Generate random graph with n nodes and m edges

Viewed 19

I don't know to start this question, should I start like this?

def make_m_graph def n,m

1 Answers

Represent a graph using a dictionary. Create a bunch of nodes. Then link nodes together.

def random_graph(num_nodes, num_edges):
    # Create a graph with all nodes, but without any edges.
    graph = {i: [] for i in range(num_nodes)}

    # Generate random node indices and link them together.
    for _ in range(num_edges):
        ...

    return graph
Related