找到一个节点的正度附近节点、附近

2023-09-11 04:52:11 作者:爱里情意绵绵

我是新来的networkx,并就如何有效地找到一个节点的n次社区其实是有点糊涂了。一个节点V_I的正度附近是一组节点的n个跳远离V_I。给定一个指定的N,我需要找了N度附近的图/网络中的每个节点。

假设我有以下的图,我想找到节点V1的N = 1个居委会。这将是v2和v3。接下来假设我想找到节点V1的N = 2个居委会,那么这将是V4。

解决方案

 导入networkx为NX
G = nx.Graph()
G.add_edges_from([('V1','V2'),('V2','V4'),('V1','V3')])

高清居委会(G,节点,N):
    path_lengths = nx.single_source_dijkstra_path_length(G,节点)
    返回[节点,节点,长度path_lengths.iteritems()
                    如果length == N]

打印(居委会(G,'V1',1))
#['V2','V3']
打印(居委会(G,'V1',2))
#['V4']
 

I'm new to networkx and actually a bit confused on how to efficiently find the n-degree neighborhood of a node. The n-degree neighborhood of a node v_i is the set of nodes exactly n hops away from v_i. Given a specified n, I need find the n-degree neighborhood for each node in the graph/network.

10.Ray Tracing Whitted Style

Suppose I have the following graph and I want to find the n=1 neighborhood of node v1. That would be v2 and v3. Next suppose I want to find the n=2 neighborhood of node v1, then that would be v4.

解决方案

import networkx as nx
G = nx.Graph()
G.add_edges_from([('v1','v2'),('v2','v4'),('v1','v3')])

def neighborhood(G, node, n):
    path_lengths = nx.single_source_dijkstra_path_length(G, node)
    return [node for node, length in path_lengths.iteritems()
                    if length == n]

print(neighborhood(G, 'v1', 1))
# ['v2', 'v3']
print(neighborhood(G, 'v1', 2))
# ['v4']