Random Graph Generation with Average Degree

  • Share this:

Code introduction


The function generates a random graph with a given number of nodes and average degree. If the average degree is less than 2, it returns an error message. If the average degree is 2, it generates a Petersen graph; if the average degree is 3, it generates a 2D cube graph; otherwise, it generates an Erdős-Rényi random graph.


Technology Stack : NetworkX

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
import random
import networkx as nx

def random_graph_properties(n, avg_degree):
    """
    Generate a random graph with n nodes and average degree avg_degree.
    The graph will be either a regular graph or a random graph depending on the value of avg_degree.
    """
    if avg_degree < 2:
        return "Average degree too low for a regular graph"
    if avg_degree == 2:
        return nx.petersen_graph()
    elif avg_degree == 3:
        return nx.cube_graph(2)
    else:
        return nx.erdos_renyi_graph(n, avg_degree / (2 * n))                
              
Tags: