2

高度に相互接続されたネットワーク内の 3 つのノードのウォークを選択して出力したいと考えています。与えられたノードから始めて、関数は、最高度の中心性を持つ隣接ノードをウォークの 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
4

1 に答える 1

1

ここに行きます(辞書の最大値のキー値を見つけることに関するこのSOの回答に触発されました):

# 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'])
于 2014-02-25T15:07:42.073 に答える