gpt4 book ai didi

python - 寻找图中的负循环

转载 作者:太空宇宙 更新时间:2023-11-03 20:23:20 24 4
gpt4 key购买 nike

我尝试了以下代码,以找到负循环。运行代码时遇到错误:“NameError:名称'NetworkXUnbounded'未定义”

我正在尝试在这里运行贝尔曼福特算法。 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)

最佳答案

在使用之前,您需要先从networkX模块导入NetworkXUnbounded。像这样的事情:

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)

还要注意,即使无向图中存在负权重边,也可能会发生此异常:

If the (di)graph contains a negative cost (di)cycle, the algorithm raises an exception to indicate the presence of the negative cost (di)cycle. Note: any negative weight edge in an undirected graph is a negative cost cycle.

参见the documentation了解更多信息。

关于python - 寻找图中的负循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58015526/

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