我想使这种dijkstra算法从文本文件(vertices.txt)中获取“ testedges”的输入,所以我希望“ testedges = myedges”能够正常工作,并让用户输入他想知道的两个顶点之间的最短路径,因此我需要使用input(),而不要像下面完整代码中所示的那样手动在代码中编写两个节点。
完整代码:
from collections import defaultdict
from heapq import *
def dijkstra(edges, f, t):
return float("inf")
if __name__ == "__main__":
testedges = [
("A", "B", 7),
("A", "D", 5),
("B", "C", 8),
("B", "D", 9),
("B", "E", 7),
("C", "E", 5),
("D", "E", 15),
("D", "F", 6),
("E", "F", 8),
("E", "G", 9),
("F", "G", 11)
]
print("=== Dijkstra ===")
print (testedges)
print ("A -> E:")
print (dijkstra(testedges, 'A', 'E'))
print ("F -> G:")
print (dijkstra(testedges, "F", "G"))
我想要的调整是:
testedges = myedges # meanning that I want the edges to come straight from the .txt file
print (input() ,"->" ,input()) # get the shortest path for the two nodes user chooses
print (dijkstra(myedges, input(), input())
.txt是以这种方式格式化的
4,3,10 // i, j, k tells you that there is an edge between vi and vj and its
weight is k.
2,1,4 // v1,v2,5 and so on for the rest
1,3,2
3,4,3
0,2,30
笔记:
对于包含如下边缘的文件:
A,B,7
C,D,8
...
你可以执行以下操作:
# 1. Reading edge info from the file
with open("vertices.txt") as f:
lines = f.readlines()
# store ordered pair of node 1, node2 and integer distance in a list
my_edges = []
for line in lines:
node1, node2, distance = (line.strip().split(','))
my_edges.append((node1,node2, int(distance)))
# similarly you can read other information like coordinates.
test_edges = my_edges
# 2. taking string input from user.
# As input required is string, we don't need to typecast
print("Enter start node")
start_node = input()
print("Enter end node")
end_node = input()
# 3. call function that returns shortest path
shortest_path = dijkstra(test_edges, start_node, end_node)
一些一般性建议:
split()
,strip()
,input()
和open()
)。它使你可以用更少的代码行执行更多操作,并提供了执行此类操作的出色示例。
我尝试运行您的代码,但在第7行“跟踪(最近一次调用,最后一次调用):文件“ C:\ Users .....”,第7行,在<module> node1,node2,distance =(line .strip()。split(','))ValueError:没有足够的值可解包(预期3,得到1)
那是因为我仅向您展示了读取边缘的示例。您仍然必须读取顶点数量(第一行中的值为1)和坐标(每行两个值)。您可以采用类似的策略来阅读它们。
抱歉,但我仍然不明白,不是test_edges应该以“'i','j',k”的格式给我边缘,然后为什么当我尝试打印test_edges时出现错误,我只想得到来自vertices.txt的格式为“'i','j',k“的边
是的,它是否应该为您提供边缘,但
lines
包含文件的所有行,这些行以其他值而不是边缘开头。