我试图使用Python中的内置Dijkstar库,并对传递add_边缘值进行查询。请帮忙
from dijkstar import find_path, Graph
graph = Graph()
input_file = input('Input the file name')
w = list()
i = 0
with open(input_file, 'r') as file:
for line in file:
for word in line.split():
w.append(word)
graph.add_edge(w[0], w[1], w[2])
print(w[0], w[1], w[2])
i = 0
w.clear()
print(find_path(graph, 1, 4))
输入文件如下,对于w[0]、w[1]和w[2]来说工作正常
1 2 1000
2 3 2000
3 4 3000
1 4 4000
输出显示错误,如下所示:
raise NoPathError('Could not find a path from {0} to {1}'.format(s, d))
dijkstar.algorithm.NoPathError: Could not find a path from 1 to 4
有一个从1到4的路径有两种方式,那么为什么它会显示错误,我们无法理解。 如果我能得到任何帮助,那就太好了
相信问题在于您不将输入转换为数字(即权重仍然是字符串)
尝试以下方法
代码
输入
file.txt
输出
评论
不需要将w声明为列表,也不需要在使用之间清除它
在对文件进行迭代时,几乎应该始终去掉尾随的“\n”
这是一种在w中放置元素的低效方法
直接分配更简单
但是,w将用字符串填充,因此需要映射到ints
变量i未使用(或不需要),因此请删除
相关问题 更多 >
编程相关推荐