Dijkstra python库将值传递到图中的add_边

2024-10-02 18:25:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用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的路径有两种方式,那么为什么它会显示错误,我们无法理解。 如果我能得到任何帮助,那就太好了


Tags: pathinfromaddforinput错误line
1条回答
网友
1楼 · 发布于 2024-10-02 18:25:44

相信问题在于您不将输入转换为数字(即权重仍然是字符串)

尝试以下方法

代码

from dijkstar import find_path, Graph

input_file = input('Input the file name: ')

with open(input_file, 'r') as file:
    graph = Graph()                     # place closer to where first used
    for line in file:
      line = line.rstrip()              # remove trailing '\n'
      w = list(map(int, line.split()))  # convert line to list of ints
      graph.add_edge(w[0], w[1], w[2])  # add edge with weights
      print(w[0], w[1], w[2])

print(find_path(graph, 1, 4))

输入

file.txt

1 2 1000 
2 3 2000 
3 4 3000 
1 4 4000

输出

PathInfo(nodes=[1, 4], edges=[4000], costs=[4000], total
_cost=4000)

评论

不需要将w声明为列表,也不需要在使用之间清除它

w = list()  # no need
w.clear()   # no need

在对文件进行迭代时,几乎应该始终去掉尾随的“\n”

 line = line.rstrip()

这是一种在w中放置元素的低效方法

for word in line.split():
    w.append(word)

直接分配更简单

 w = line.split()

但是,w将用字符串填充,因此需要映射到ints

 w = list(map(int, line.split()))

变量i未使用(或不需要),因此请删除

i = 0

相关问题 更多 >