Dijkstra的算法打印太多了

时间:2014-02-08 00:40:21

标签: python printing dijkstra sys

所以我在这里有这个代码,它采用图表然后打印所选择的两个点之间的最短距离。它的输入是python filename.py start end 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}}

唯一的问题是,当它在Command中打印输出时,它会打印出来,如下所示:
从开始到结束的距离是(距离,[开始,结束]) 我无法弄清楚如何在没有任何括号或起点和终点的情况下打印距离。任何帮助表示赞赏      “””         2014年冬季         作者:Cole Charbonneau&彼得Pham         信用:Python: Importing a graph             Stackoverflow帮助我们弄清楚如何通过sys.argv

导入图形
    Finds the shortest path between two points in a dictionary graph.
    Uses a single-source shortest distance approach, nearly identical to
        Dijkstra's Algortihm.

    Takes input in the format: python filename.py start end grap.txt
    """
    import sys

    def shortestpath(graph,start,end,visited=[],distances={},predecessors={}):
        """Finds the shortest path between a start and end point from a graph"""

        if start==end:
            path=[]                             ##If the starting point is the end point, then we're done

            while end != None:
                path.append(end)
                end=predecessors.get(end,None)

            return distances[start], path[::-1]
                                                ##Check if it's the first time through it, and set current distance to 0
        if not visited: distances[start]=0
                                                ##Runs through each adjacent point, and keeps track of the preceeding ones
        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
                                                ##Now that all of the adjacent points are visited, we can mark the current point as visited
        visited.append(start)
                                                ##This finds the next closest unvisited point to start on
        unvisiteds = dict((k, distances.get(k,sys.maxsize)) for k in graph if k not in visited)
        closestvertex = min(unvisiteds, key=unvisiteds.get)
                                                ##Recurses that closest point making it the current one
        return shortestpath(graph,closestvertex,end,visited,distances,predecessors)




    if __name__ == "__main__":
        start = sys.argv[1]
        end = sys.argv[2]
        graph = eval(open(sys.argv[3],'r').read())
        if len(sys.argv) != 4:
            print('Input syntax: python filename.py start end map.py')
        else:
            print('Distance from ',start,' to ',end,' is ',shortestpath(graph,start,end))


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

1 个答案:

答案 0 :(得分:0)

该函数返回tuple,因此您需要访问元组中的第一个元素

length = shortestpath(graph,start,end)[0]

或解压缩:

length, path = shortestpath(graph,start,end)