You can download this code by clicking the button below.
This code is now available for download.
This function accepts a NetworkX graph object and returns a dictionary containing randomly selected node, edge, node degree, number of connected components, average path length, and degree distribution.
Technology Stack : NetworkX
Code Type : Function
Code Difficulty : Intermediate
import networkx as nx
import random
def random_graph_properties(G):
"""
Generate random properties for a given graph G using NetworkX.
:param G: A networkx.Graph object.
:return: A dictionary with random graph properties.
"""
# Randomly choose a node from the graph
node = random.choice(list(G.nodes()))
# Randomly choose an edge from the graph
edge = random.choice(list(G.edges()))
# Calculate the degree of the chosen node
degree = G.degree(node)
# Calculate the number of connected components
connected_components = len(list(nx.connected_components(G)))
# Calculate the average path length of the graph
average_path_length = nx.average_shortest_path_length(G)
# Randomly choose a node's degree distribution
degree_distribution = nx.degree_distribution(G)
# Generate the result dictionary
result = {
"node": node,
"edge": edge,
"degree": degree,
"connected_components": connected_components,
"average_path_length": average_path_length,
"degree_distribution": degree_distribution
}
return result
# Example usage:
# G = nx.erdos_renyi_graph(10, 0.5)
# properties = random_graph_properties(G)
# print(properties)