'Chosing random node among nodes with highest attribute value

I want to select and print a walk of three nodes in a highly interconnected network. Starting with a given node, the function should select as a second node for the walk that adjacent node with the highest degree centrality.

In the case of a tie, I want to have the programme randomly select between these nodes.

Here's what I have so far:

import networkx as nx
from random import choice
g =nx.Graph()
g.add_nodes_from(range(1,5))
g.add_edges_from([(1,5),(2,5),(3,5),(4,5), (1,2),(2,3),(3,4),(4,5)])

nx.set_node_attributes(g,'degree_cent',nx.degree_centrality(g))
degree_walk =[]                 

node1=g.nodes()[2]
degree_walk.append(node1)
for node2 in g.neighbors(node1):
    if max(g.node[node2]['degree_cent'],  g.node[node2]['degree_cent'].get):
            node2 = choice(g.neighbors(node1))
            degree_walk.append(node2)
print degree_walk


Solution 1:[1]

Here you go (inspired by this SO answer on finding key value of max value of dictionary):

# Find all the neighbors with maximum centrality:
highest_centrality = max([g.node[n]['degree_cent'] 
                          for n in g.neighbors(node1)) 
most_central_neighbors = [n for n in g.nodes() 
                          if g.node[n]['degree_cent'] == highest_centrality]
# Pick one at random:
random_central_neighbor = choice([most_central_neighbors])
# Add it to the list:
degree_walk.append(random_central_neighbor)
print degree_walk

Note that if you don't care about ties (and are happy to accept the first one in the order of the original list) you can do:

# Find all the neighbors with maximum centrality:
most_central_neighbors = max(g.neighbors(node1), 
                             key=lambda(n): g.node[n]['degree_cent'])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sergey Antopolskiy