Python无法运行程序

时间:2018-07-05 15:25:42

标签: python dijkstra

我是python的新手,但是具有C#和Matlab的大学经验。我正在尝试编写并运行dijkstras算法,但是当我运行它时,什么也没发生。我将附上代码(包括注释掉的失败尝试),以希望有人可以指导我朝正确的方向发展。

#must write script to turn matrix into this form of graph
graph = {'a':{'c':3,'e':5},'c':{'a':3,'d':5},'d':{'c':3,'e':6},'e':
{'d':6,'a':5}}
unseenNodes = {}
goal = {}
start = {}


#defining function
def dijkstra(graph, start, goal):
    shortest_distance = {} #empty dictionary
    predeccesor = {} #empty dictionary 
    unseenNodes = graph #makes it run through til all are seen
    path = []
def __init__(self):  
 #start node to next node
    print( str("hi"))

     for node in unseenNodes:
        shortest_distance[node]=9999999
        shortest_distance[start]=0
        print(shortest_distance)

#beefy bit of dijkstras alogrithim 
    while unseenNodes:
        minNode=None
        for node in unseenNodes:
            if minNode is None:
                minNode = node

            elif shortest_distance[node] < shortest_distance[minNode]:
                minNode = node

            for childNode, weight in graph [minNode].items():
                if weight + shortest_distance[minNode] < 
 shortest_distance[childNode]:
                    shortest_distance[childNode] = weight + shortest_distance[minNode]

                predeccesor[childNode] = minNode
                unseenNodes.pop(minNode)

                print(shortest_distance)

#reverse stack approach to trace path
    currentNode = goal
    while currentNode != start:
        try:
            path.insert(0,currentNode)
            currentNode = predeccesor[currentNode]
         except KeyError:
            print('path not valid')
        #break

        path.insert(0,start)
        if shortest_distance[goal] != infinity:
            #print(goal) 
            print('shortest distance is' + str(shortest_distance[goal]))
            print('path is' + str(path))
         else:
             Print('Something Went Wrong!')

#break

dijkstra(graph, 'a', 'd')

3 个答案:

答案 0 :(得分:2)

您的dijkstra函数仅执行这四行代码,因为它们是定义第二个函数之前的唯一几行代码。因此,当您最后调用此函数时,程序将创建一些空字典,然后关闭:

shortest_distance = {} #empty dictionary
predeccesor = {} #empty dictionary 
unseenNodes = graph #makes it run through til all are seen
path = []

您定义的第二个函数 init ()是一个类方法,您不能在类外部定义它。

首先查看python中的一些更基本的算法,并熟悉语法(我不知道它与C#有何不同)。

答案 1 :(得分:0)

好的,所以我修复了代码的缩进,作用域和名称问题(请参见下文),并且出现了以下错误

hi
{'a': 0}
{'a': 0, 'c': 9999999}
{'a': 0, 'c': 9999999, 'd': 9999999}
{'a': 0, 'c': 9999999, 'd': 9999999, 'e': 9999999}
{'a': 0, 'c': 3, 'd': 9999999, 'e': 9999999}
Traceback (most recent call last):
  File "dijkstras.py", line 69, in <module>
    dijkstra(graph, 'a', 'd')
  File "dijkstras.py", line 47, in dijkstra
    unseen_nodes.pop(minNode)
KeyError: 'a'

也许这可以帮助您继续吗?

#! /usr/bin/env python3
# dijkstras.py

import math

# must write script to turn matrix into this form of graph
graph = {
    'a': {'c': 3, 'e': 5},
    'c': {'a': 3, 'd': 5},
    'd': {'c': 3, 'e': 6},
    'e': {'d': 6, 'a': 5}
}


# defining function
def dijkstra(graph, start, goal):
    shortest_distance = {}  # empty dictionary
    predeccesor = {}  # empty dictionary
    unseen_nodes = graph  # makes it run through til all are seen
    path = []

    # start node to next node
    print(str("hi"))

    for node in unseen_nodes:
        shortest_distance[node] = 9999999
        shortest_distance[start] = 0
        print(shortest_distance)

    # beefy bit of dijkstras alogrithim
    while unseen_nodes:
        min_node = None
        for node in unseen_nodes:
            if min_node is None:
                min_node = node

            elif shortest_distance[node] < shortest_distance[min_node]:
                min_node = node

            for childNode, weight in graph[min_node].items():
                if weight + shortest_distance[min_node] < shortest_distance[childNode]:
                    shortest_distance[childNode] = weight + shortest_distance[min_node]

                    predeccesor[childNode] = min_node
                    unseen_nodes.pop(min_node)

                    print(shortest_distance)

                    # reverse stack approach to trace path
    current_node = goal
    while current_node != start:
        try:
            path.insert(0, current_node)
            current_node = predeccesor[current_node]
        except KeyError:
            print('path not valid')
        # break

        path.insert(0, start)
        if shortest_distance[goal] != math.inf:
            # print(goal)
            print('shortest distance is' + str(shortest_distance[goal]))
            print('path is' + str(path))
        else:
            print('Something Went Wrong!')



if __name__ == '__main__':  # only run if script
    dijkstra(graph, 'a', 'd')

答案 2 :(得分:0)

您只需进行一次更改

  • 从代码中删除该def __init__(self): function
  • __ init __ 函数在 class 中用于初始化 对象的变量。

  • 您无法调用__init__函数,这就是为什么您未获得任何输出的原因。

  • 也可以执行适当的 indentation ,您将获得输出。