I have the following graph and the function to find second-order neighbors of a node in the graph:
import networkx as nx
G = nx.Graph()
G.add_edge('1','2',weight=673)
G.add_edge('2','4',weight=201)
G.add_edge('4','1',weight=20)
G.add_edge('2','3',weight=96)
G.add_edge('3','4',weight=44)
G.add_edge('6','3',weight=7)
G.add_edge('6','4',weight=96)
G.add_edge('5','6',weight=10)
G.add_edge('7','6',weight=10)
G.add_edge('8','6',weight=10)
def neighbors_r2(node):
subgraph = nx.ego_graph(G,str(int(node)),center=False,radius=2)
return list(subgraph.nodes())
print(f"second order neighbors are: {neighbors_r2(6)}.")
My problem is that the result must be ['1', '2', '3', '4']
, but the result of the code is ['1', '2', '4', '3', '5', '7', '8']
. I understood the reason is because that ego_graph
includes all neighbors of distance<=radius (here node). How can I change the function so that only returns nodes with second-order neighbors?
You can use a set
comprehension and Graph.neighbors
:
def second_order_neighbors(G, node):
return set(x for n in G.neighbors(node) for x in G.neighbors(n))-{node}
second_order_neighbors(G, '6')
Output: {'1', '2', '3', '4'}