Warm tip: This article is reproduced from serverfault.com, please click

其他-使dijkstra算法从python中的.txt文件获取输入

(其他 - make dijkstra algorithm take input from .txt file in python)

发布于 2020-11-28 22:59:55

我想使这种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

笔记:

Questioner
Ryu
Viewed
12
Shivam Miglani 2020-11-29 18:14:27

对于包含如下边缘的文件:

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)

一些一般性建议:

  • 使用描述性的,易读的变量名(例如,不使用myarray)
  • 阅读标准功能python文档了Python为字符串和文件(split()strip()input()open())。它使你可以用更少的代码行执行更多操作,并提供了执行此类操作的出色示例。