使用NetworkX all_simple_paths给出了AttributeError

时间:2015-11-03 13:23:54

标签: python networkx adjacency-matrix

我有一个带有以下形式的邻接矩阵的图形(一个6节点图,其中自边为0,no_connections标记为Inf,其他边为1):

{1: {1: 0, 2: 1, 3: inf, 4: inf, 5: inf, 6: inf}, 2: {1: 1, 2: 0, 3: inf, 4: 1, 5: 1, 6: inf}, 3: {1: inf, 2: inf, 3: 0, 4: 1, 5: inf, 6: inf}, 4: {1: inf, 2: 1, 3: 1, 4: 0, 5: 1, 6: 1}, 5: {1: inf, 2: 1, 3: inf, 4: 1, 5: 0, 6: inf}, 6: {1: inf, 2: inf, 3: inf, 4: 1, 5: inf, 6: 0}}

我想在其all_simple_paths函数中使用networkx包来查找从源到目的地的所有简单路径但是当我调用时

nx.all_simple_paths(graph, src, dst)
它给出了: AttributeError:'dict'对象没有属性'is_multigraph'

我目前没有任何其他格式的图表。我该如何解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:1)

您的图表目前存储为字典。期望networkx在您选择的任何数据结构上自动运行有点不公平。即使它被设置为以你已经完成的方式处理字典,它如何知道如何解释0或inf

要使用networkx命令,您需要将图表设置为networkx图形格式。

import networkx as nx
D = {1: {1: 0, 2: 1, 3: float('inf'), 4: float('inf'), 5: float('inf'), 6: float('inf')}, 2: {1: 1, 2: 0, 3: float('inf'), 4: 1, 5: 1, 6: float('inf')}, 3: {1: float('inf'), 2: float('inf'), 3: 0, 4: 1, 5: float('inf'), 6: float('inf')}, 4: {1: float('inf'), 2: 1, 3: 1, 4: 0, 5: 1, 6: 1}, 5: {1: float('inf'), 2: 1, 3: float('inf'), 4: 1, 5: 0, 6: float('inf')}, 6: {1: float('inf'), 2: float('inf'), 3: float('inf'), 4: 1, 5: float('inf'), 6: 0}}

G=nx.Graph()
for node, neighbor_dict in D.items():
    G.add_node(node)
    for neighbor, val in neighbor_dict.items():
        if val !=0 and val <float('inf'):
            G.add_edge(node, neighbor, weight=val)

for path in nx.all_simple_paths(G,1,3):
    print path
>[1, 2, 4, 3]
>[1, 2, 5, 4, 3]