gpt4 book ai didi

networkx - 常见的 'out' 邻居和常见的 'in' 邻居

转载 作者:行者123 更新时间:2023-12-05 01:04:50 26 4
gpt4 key购买 nike

从有向图中并给出两个顶点 (v, u) 我需要找到:共同的“出”邻居和共同的“入”邻居。

例如:

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")

Directed Graph

我要这个:
# 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'])

我可以拥有常见的“外出”邻居:
def common_out_neighbors(g, i, j):
return set(g.neighbors(i)).intersection(g.neighbors(j))

但是,我不知道如何获得 Common 'in' Neigbors。谁能帮我?

最佳答案

对于有向图,您可以使用 predecessorssuccessors方法:

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'])

关于networkx - 常见的 'out' 邻居和常见的 'in' 邻居,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22458000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com