2013-05-20 112 views
2

我想選擇並打印一個高度互連的網絡中的三個節點。從給定節點開始,函數應該選擇第二個節點作爲步行的最高度中心度的相鄰節點。在具有最高屬性值的節點之間選擇隨機節點

在平局的情況下,我想讓程序在這些節點之間隨機選擇。

這是我到目前爲止有:

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 
+0

嘿和welc青梅。只是一個友好的建議。當你在這裏寫問題時,你應該儘量避免長時間連續的文本。祝你好運! –

回答

1

在這裏你去(由this SO answer上找到詞典的最大價值的關鍵值的啓發):

# 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 

請注意,如果你不這樣做關心關係(並且很樂意接受原始列表中的第一個)你可以這樣做:

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