从有向图中给出两个顶点(v,u),我需要找到:Common' out'邻居和共同' in'邻居。
E.g:
import networkx as nx
ghybrid = nx.DiGraph()
ghybrid.add_edge("A", "B")
ghybrid.add_edge("A", "C")
ghybrid.add_edge("B", "D")
ghybrid.add_edge("D", "C")
ghybrid.add_edge("E", "A")
ghybrid.add_edge("E", "D")
我想要这个:
# Common out Neighbors
B , E : set(['D'])
E , B : set(['D'])
A , D : set(['C'])
D , A : set(['C'])
# Common in Neighbors
A , D : set(['E'])
D , A : set(['E'])
我可以拥有Common' out'邻居:
def common_out_neighbors(g, i, j):
return set(g.neighbors(i)).intersection(g.neighbors(j))
但是,我不知道如何让Common' in' Neigbors。任何人都可以帮助我吗?
答案 0 :(得分:4)
对于DiGraphs,您可以使用predecessors
和successors
方法:
import networkx as nx
def common_out_neighbors(g, i, j):
return set(g.successors(i)).intersection(g.successors(j))
def common_in_neighbors(g, i, j):
return set(g.predecessors(i)).intersection(g.predecessors(j))
if __name__ == '__main__':
ghybrid = nx.DiGraph()
ghybrid.add_edge("A", "B")
ghybrid.add_edge("A", "C")
ghybrid.add_edge("B", "D")
ghybrid.add_edge("D", "C")
ghybrid.add_edge("E", "A")
ghybrid.add_edge("E", "D")
print common_out_neighbors(ghybrid, 'A', 'D')
print common_in_neighbors(ghybrid, 'A', 'D')
# output
# set(['C'])
# set(['E'])