【发布时间】:2014-06-18 12:38:47
【问题描述】:
我有一个networkx 图G,我使用此代码计算了距离特定节点 2-hubs 的节点:
def node_neighborhood(G, node, n=2):
"""
Returns a list of nodes which are the n-neighborhood of the input node.
Parameters
----------
G: networkx graph object.
node: the node to get the neighborhood for.
n: the neighborhood degree.
"""
path_lengths = nx.single_source_dijkstra_path_length(G, node)
return [node for node, length in path_lengths.iteritems()
if length == n]
所以这段代码返回的节点是距离指定节点 2-hubs 的节点。
接下来,我使用以下代码从G 中删除了不在node_neighborhood 返回列表中的所有节点:
for n in G.nodes():
if (n not in node_2_neiborhood) and (n != node):
G.remove_node(n)
else:
if G.degree(n) == 0:
raise Exception("a node has zero degree!!!")
但是问题是节点的度数为零的异常被抛出。我的问题是为什么会这样?如果一个节点距离 X 2-hubs,那么该节点必须至少有一条边!那么邻域中的一个节点怎么可能是零度呢?!
【问题讨论】:
标签: python algorithm graph networkx