Search code examples
python-3.xgraphnetworkx

average degree of a node


The question is: Write a Python function that accepts a NetworkX graph and a node name and returns the average degree of that node's neighbors. Use this function to compute this quan-tity for every node in the OpenFlights US network and take the average. Does the Friendship Paradox hold here (i.e. is the average degree of nearest neighbors greater than the average node degree)?

def averagedegree(G,node)
    for node in G.neighbors(node)
    2 * V.number_of_edges(node) / V.number_of_nodes(node) ```

and then I want to return a dict of the average degree of the neighbors BUT the average number of nodes and number of edges BOTH accept no arguments

Solution

  • The average degree of the node's neighbours is the sum of the degrees of each neighbour, divided by the number of neighbours. The number of neighbours of a node is exactly its degree.

    The degree of a node u in a networkx Graph G is G.degree(u).

    In python, the sum can easily be obtained with builtin function sum.

    Relevant documentation:

    def average_degree(G, u):
        return sum(G.degree(v) for v in G.neighbors(u)) / G.degree(u)
    

    Note that this function will raise ZeroDivisionError if u has no neighbours.

    Testing with a custom graph:

    from networkx import Graph
    
    G = Graph()
    G.add_edges_from([(0, 2), (0, 7), (2, 1), (2, 9), (2, 8), (1, 8), (1, 3), (9, 6), (9, 4), (9, 7), (8, 7), (8, 5), (8, 6), (7, 5), (7, 6)])
    
    avg_degrees_dict = { u: average_degree(G,u) for u in G.nodes }
    
    print(avg_degrees_dict)
    # {0: 4.5,
    #  1: 3.3333333333333335,
    #  2: 3.5,
    #  3: 3.0,
    #  4: 4.0,
    #  5: 5.0,
    #  6: 4.666666666666667,
    #  7: 3.2,
    #  8: 3.4,
    #  9: 3.25}