【问题标题】:Python: all shortest paths in disconnected components of a graphPython:图的断开组件中的所有最短路径
【发布时间】:2016-05-06 10:35:11
【问题描述】:

我正在计算常规网络中任意两个节点之间所有可能的最短路径。如果网络是连接的(例如,最大的组件=整个网络),我没有问题。

当我断开组件时出现问题:假设节点n 和节点j 之间没有路径,则会引发NetworkXNoPath 错误。

我的问题: 我想跳过所有未连接的节点对。我知道我需要一个 if 来检查是否存在错误提出,但我不知道如何将其添加到我的代码中。

我的代码用于计算图中任意两个节点之间所有可能的最短路径:

    import networkx as nx
    counts=OrderedDict()
    for n in F.nodes(): counts[n]=0
    for n in F.nodes():
        for j in F.nodes():
            if (n!=j):
                gener=nx.all_shortest_paths(F,source=n,target=j)
                for p in gener:
                    for v in p: counts[v]+=1

回顾一下:我可以使用nx.bidirectional_dijkstra(F, n, j) 来检查节点n 和节点j 之间是否存在一条边,如果这样的边是,它会引发NetworkXNoPatherror丢失,但是如何检查此错误以跳过一对未连接的节点?

【问题讨论】:

  • 您尝试过使用 try 并且除此之外。你可以试试:nx.bidirectional_dijkstra(F, n, j) except NetworkXNoPath: #do what you want.
  • 其实这个案例我不知道怎么用,不过我想这就是答案……

标签: python for-loop error-handling exception-handling networkx


【解决方案1】:

只需对每个连接的组件进行计算。检查两个节点之间是否没有路径的测试可能很昂贵。

connected_components = nx.connected_component_subgraphs(G)
for component in connected_components:
    #your code here.                            

【讨论】:

【解决方案2】:

您可以为此使用 python 中的错误处理。

try:
  nx.bidirectional_dijkstra(F, n, j)
except NetworkXNoPath:
  # do whatever you want

您可以使用此link 获取更多帮助

【讨论】:

  • 实际上缺少一个nx.,但这很好用。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
  • 2012-07-07
  • 1970-01-01
相关资源
最近更新 更多