的Python:导入图Python

2023-09-11 07:00:14 作者:夢巳瑆丶悇溫潵浕

所以我有这个code在这里,基本上运行Dijkstra的Algortihm在Python中的图形,然后打印出的距离和移动才能到达从开始到结束。我的问题是,我无法弄清楚如何导入图形作为使用sys.argv中一个txt文件,并把它读它,并在其上​​运行的算法。这是我的code,用图表,并开始'a'和结束的'B'已经装入了。 (它应该工作)。

So I have this code here, which basically runs Dijkstra's Algortihm on a graph in Python, and then prints the distance and moves it takes to get from start to end. My problem is, I can't figure out how to import a graph as a .txt file using sys.argv and have it read it and run the algorithm on it. Here is my code, with a graph and start 'a' and end 'b' already filled into it. (It should work).

import sys

def shortestpath(graph,start,end,visited=[],distances={},predecessors={}):
    """Find the shortest path between start and end nodes in a graph"""
    # we've found our end node, now find the path to it, and return
    if start==end:
        path=[]
        while end != None:
            path.append(end)
            end=predecessors.get(end,None)
        return distances[start], path[::-1]
    # detect if it's the first time through, set current distance to zero
    if not visited: distances[start]=0
    # process neighbors as per algorithm, keep track of predecessors
    for neighbor in graph[start]:
        if neighbor not in visited:
            neighbordist = distances.get(neighbor,sys.maxsize)
            tentativedist = distances[start] + graph[start][neighbor]
            if tentativedist < neighbordist:
                distances[neighbor] = tentativedist
                predecessors[neighbor]=start
    # neighbors processed, now mark the current node as visited
    visited.append(start)
    # finds the closest unvisited node to the start
    unvisiteds = dict((k, distances.get(k,sys.maxsize)) for k in graph if k not in visited)
    closestnode = min(unvisiteds, key=unvisiteds.get)
    # now we can take the closest node and recurse, making it current
    return shortestpath(graph,closestnode,end,visited,distances,predecessors)



if __name__ == "__main__":
    graph = {'a': {'w': 14, 'x': 7, 'y': 9},
            'b': {'w': 9, 'z': 6},
            'w': {'a': 14, 'b': 9, 'y': 2},
            'x': {'a': 7, 'y': 10, 'z': 15},
            'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11},
            'z': {'b': 6, 'x': 15, 'y': 11}}
    print(shortestpath(graph,'a','b'))


    """
    Result:
        (20, ['a', 'y', 'w', 'b'])
        """

现在这里是我试图导入图形,它被称为采样map.txt:

Now here is the graph that I am trying to import, it is called sample-map.txt:

{'a': {'b': 5, 'c': 8},
'b': {'a': 5, 'd': 6},
'c': {'a': 8, 'd': 2},
'd': {'b': 6, 'c': 2, 'e': 12, 'f': 2},
'e': {'d': 12, 'g': 3},
'f': {'d': 2, 'g': 7},
'g': {'e': 3, 'f':7}}

我只需要弄清楚如何使用sys.argv中导入它,然后把它在的.py取图的地方了。此外,能够使用sys.argv中定义的起点和终点将是很好过,像在格式>蟒蛇file.py开始结束采样map.txt 其中,

I just need to figure out how to import it using sys.argv and then have it take the place of the graph already in the .py. Also, being able to use sys.argv to define a starting point and end point would be nice too, something like in the format >python file.py start end sample-map.txt Where

sys.argv[0] is file.py
sys.argv[1] is start
sys.argv[2] is end,
and sys.argv[3]

是我想要导入的图形。谢谢!

is the graph I want to import. Thank you!

推荐答案

如果 sys.argv中[3] 是文件中包含要导入图形的名称,您可以使用 ast.literal_eval :

If sys.argv[3] is the name of the file containing the graph you want to import, you can use ast.literal_eval:

with open(sys.argv[3], "r") as f:
    graph = ast.literal_eval(f.read())
# If you don't trust your users, check that graph is indeed a dict
# and that it has the right structure