我尝试了以下代码,以找到负循环。运行代码时遇到错误:“ NameError:未定义名称'NetworkXUnbounded'”
我正在尝试在此处运行bellman-ford算法。 Algo引发了一个类型为“ NetworkXUnbounded”的异常,我尝试使用下面显示的异常处理来处理。
import pandas as pd
import networkx as nx
import numpy as np
df = pd.read_csv("fx_rate_3.csv")
G = nx.from_pandas_edgelist(df,source='A', target='B', edge_attr ['weight'], create_using=nx.DiGraph())
def find_path(digraph, start):
try:
path = nx.bellman_ford_predecessor_and_distance(digraph, start, 'weight')
return path
except NetworkXUnbounded:
cycles = nx.simple_cycles(digraph)
for cycle in cycles:
print (cycle)
答案 0 :(得分:0)
在使用之前,您需要先从NetworkXUnbounded
模块导入networkX
。像这样:
import pandas as pd
import networkx as nx
import numpy as np
from networkx import NetworkXUnbounded # <---- Import the exception before using it
df = pd.read_csv("fx_rate_3.csv")
G = nx.from_pandas_edgelist(df,source='A', target='B', edge_attr ['weight'], create_using=nx.DiGraph())
def find_path(digraph, start):
try:
path = nx.bellman_ford_predecessor_and_distance(digraph, start, 'weight')
return path
except NetworkXUnbounded:
cycles = nx.simple_cycles(digraph)
for cycle in cycles:
print (cycle)
还要注意,即使无向图中存在负权重边缘,也会发生此异常:
如果(di)图包含负成本(di)周期,则该算法会引发异常,以指示存在负成本(di)周期。注意:无向图中的任何负权重边缘都是负成本周期。
有关更多信息,请参见the documentation。