2

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
Sergey Antopolskiy
  • 3,970
  • 2
  • 24
  • 40
leos2013
  • 21
  • 2
  • Hey and welcome. Just a friendly suggestion. When you write questions here, you should try to avoid long consecutive lines of text. Good luck! – Benjamin Gruenbaum May 20 '13 at 19:00

1 Answers1

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'])
Sergey Antopolskiy
  • 3,970
  • 2
  • 24
  • 40
LondonRob
  • 73,083
  • 37
  • 144
  • 201