Using NetworkX all_simple_paths gives AttributeError
我有一个具有以下形式的邻接矩阵的图形(一个6节点图形,其中自边缘为0,no_connections标记为Inf,其他边缘为1):
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}} |
我想使用networkx包的all_simple_paths函数来查找从源到目的地的所有简单路径,但是当我调用
时
1 | nx.all_simple_paths(graph, src, dst) |
它给出:
AttributeError:'dict'对象没有属性'is_multigraph'
我目前没有任何其他格式的图表。我应该如何解决此问题?
谢谢。
您的图形当前存储为字典。期望networkx可以自动处理您选择的任何数据结构有点不公平。即使将其设置为以您执行字典的方式处理字典,它如何知道如何解释0或
要使用networkx命令,您需要图形为networkx图形格式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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] |