简体   繁体   English

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

[英]make dijkstra algorithm take input from .txt file in python

i'm trying to make this dijkstra algorithm take input for "testedges' from a text file (vertices.txt) so I want 'testedges = myedges' to work without errors. and make the user enters the two vertices that he wants to know the shortest path between, so I need to use input() and don't manually write the two nodes in the code like it's shown below in the full code.我试图让这个dijkstra算法从文本文件(vertices.txt)中获取“testedges”的输入,所以我希望“testedges = myedges”能够正常工作。并使用户输入他想知道的两个顶点之间的最短路径,所以我需要使用 input() 并且不要在代码中手动编写两个节点,如下面的完整代码所示。

The full code:完整代码:

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"))

the adjustment I want are:我想要的调整是:

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 is formatted this way .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

note:笔记:

For file which contains edges like:对于包含边缘的文件,例如:

A,B,7
C,D,8
... 

You can do something like:您可以执行以下操作:

# 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)

Some general advice:一些一般性建议:

  • Use descriptive, readable variable names (eg not myarray)使用描述性、可读性的变量名(例如不是 myarray)
  • read python docs for standard functionality that Python provides for strings and files ( split() , strip() , input() and open() ).阅读 python 文档,了解 Python 为字符串和文件( split()strip()input()open() )提供的标准功能。 It allows you to do more in less lines of code and has nice examples of doing such things.它允许你用更少的代码行做更多的事情,并且有很好的例子来做这些事情。

A possible solution is:一个可能的解决方案是:

A configuration file, named dijkstra.config , having the following content:一个名为dijkstra.config的配置文件,具有以下内容:

[PARAMETERS]
node_numbers: 5
coordinates: (1, 10),(8, 10),(10, 8),(7, 4),(3, 1)
nodes: (0,1,10),(1,2,5),(2,3,25),(0,3,3),(3,4,8)

You can check how to use it running in a python file test.py the following code:您可以在 python 文件test.py中检查如何使用它运行以下代码:

import configparser

config = configparser.ConfigParser()
config.read("dijkstra.config")

print("number of nodes:\n" ,config["PARAMETERS"]["node_numbers"])
print("coordinates:\n", config["PARAMETERS"]["coordinates"])
print("nodes:\n", config["PARAMETERS"]["nodes"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM