gpt4 book ai didi

python - Networkx-寻找多向图的平行边

转载 作者:太空宇宙 更新时间:2023-11-03 21:10:43 25 4
gpt4 key购买 nike

我有一个像这样的多向图-

Import Networkx as nx

G=nx.MultiDiGraph()
G.add_edge(0,1)
G.add_edge(1,0)
G.add_edge(1,3)

有什么networkx方法可以找到边0-1和1-0是平行的吗?

最佳答案

据我所知,没有内置的networkx函数可以解决这个问题。但是 networkx 将图节点和边存储在可迭代结构中,因此您可以像这样一一处理它们:

# For every node in graph
for node in G.nodes():
# We look for adjacent nodes
for adj_node in G[node]:
# If adjacent node has an edge to the first node
# Or our graph have several edges from the first to the adjacent node
if node in G[adj_node] or len(G[node][adj_node]) > 1:
# DO MAGIC!!
print(node, adj_node)

我认为这是可以解决您的问题的最networkx的代码。请注意,图越稀疏,运行速度越快。在最坏的情况下 - 完整的图 - 复杂度为 O(n^2)。在最好的情况下 - 非常稀疏的图 - O(n)。

关于python - Networkx-寻找多向图的平行边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55084838/

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