首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Dijkstra算法打印太多

Dijkstra算法打印太多
EN

Stack Overflow用户
提问于 2014-02-08 08:40:21
回答 1查看 189关注 0票数 0

所以我在这里有这样的代码,它获取一个图,然后打印出所选两点之间的最短距离。它的输入是python filename.py start end map.txt,它可以很好地处理我给出的图表,如下所示:

代码语言:javascript
复制
{'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}}

唯一的问题是,当它在命令中打印输出时,它是这样打印的:

从起点到终点的距离是(distance,start,end)我不知道如何打印没有括号或起点和终点的距离。任何帮助都是非常感谢的。

代码语言:javascript
复制
  """         Winter 2014         Authors: Cole Charbonneau & Peter Pham         Credit: [Python: Importing a graph](https://stackoverflow.com/questions/21628503/python-importing-a-graph?noredirect=1)             Stackoverflow for helping us figure out how to import a graph via sys.argv
代码语言:javascript
复制
    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'])
            """
EN

回答 1

Stack Overflow用户

发布于 2014-02-08 09:07:00

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

代码语言:javascript
复制
length = shortestpath(graph,start,end)[0]

或者将其解包:

代码语言:javascript
复制
length, path = shortestpath(graph,start,end)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21640319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档