Random Graph Properties Analysis

  • Share this:

Code introduction


This function takes a graph as input and returns a dictionary containing random properties of the graph such as degree, diameter, average path length, and betweenness centrality for a randomly selected node.


Technology Stack : NetworkX

Code Type : Function

Code Difficulty : Intermediate


                
                    
import networkx as nx
import random

def random_graph_properties(graph):
    """
    This function takes a graph as input and returns a dictionary containing
    random properties of the graph such as degree, diameter, average path length,
    and betweenness centrality for a randomly selected node.
    """
    # Check if the graph is empty
    if graph.number_of_nodes() == 0:
        return "Graph is empty"

    # Calculate the degree of the graph
    degree = graph.number_of_nodes() - graph.number_of_edges()

    # Calculate the diameter of the graph
    diameter = nx.diameter(graph)

    # Calculate the average path length of the graph
    average_path_length = nx.average_shortest_path_length(graph)

    # Randomly select a node from the graph
    node = random.choice(list(graph.nodes()))

    # Calculate the betweenness centrality of the randomly selected node
    betweenness_centrality = nx.betweenness_centrality(graph)[node]

    return {
        "degree": degree,
        "diameter": diameter,
        "average_path_length": average_path_length,
        "betweenness_centrality": betweenness_centrality
    }

# Example usage:
# G = nx.erdos_renyi_graph(10, 0.5)
# print(random_graph_properties(G))                
              
Tags: