Python赢得了';t运行程序

Python赢得了';t运行程序,python,dijkstra,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}} unseenN

我是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')
#必须编写脚本才能将矩阵转换为这种图形形式
图={'a':{'c':3,'e':5},'c':{'a':3,'d':5},'d':{'c':3,'e':6},'e':
{'d':6,'a':5}
未选定节点={}
目标={}
开始={}
#定义功能
def dijkstra(图表、开始、目标):
最短距离={}空字典
predecesor={}#空字典
Unseenodes=图形#使其贯穿整个屏幕,直到看到所有内容
路径=[]
定义初始化(自):
#从开始节点到下一个节点
打印(str(“hi”))
对于未选定节点中的节点:
最短距离[节点]=999999
最短距离[起点]=0
打印(最短距离)
#强壮的迪杰克斯特拉斯向他抛媚眼
在未选定时:
minNode=None
对于未选定节点中的节点:
如果minNode为None:
minNode=节点
elif最短_距离[节点]<最短_距离[节点]:
minNode=节点
对于childNode,图[minNode]中的权重。项()
如果重量+最短距离[minNode]<
最短距离[子节点]:
最短_距离[childNode]=权重+最短_距离[minNode]
predecesor[childNode]=minNode
未命名。pop(minNode)
打印(最短距离)
#跟踪路径的反向堆栈方法
当前节点=目标
而currentNode!=开始:
尝试:
插入路径(0,currentNode)
currentNode=predecesor[currentNode]
除KeyError外:
打印('路径无效')
#中断
路径.插入(0,开始)
如果最短距离[目标]!=无穷:
#打印(目标)
打印('最短距离为'+str(最短距离[目标]))
打印('路径为'+str(路径))
其他:
打印(“出了问题!”)
#中断
dijkstra(图'a','d')

好的,我解决了一系列代码的缩进、范围和名称问题(见下文),出现了以下错误

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'
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}
回溯(最近一次呼叫最后一次):
文件“dijkstras.py”,第69行,在
dijkstra(图'a','d')
文件“dijkstras.py”,第47行,在dijkstra中
不可见的_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')
#/usr/bin/env蟒蛇3
#迪克斯特拉斯比
输入数学
#必须编写脚本才能将矩阵转换为这种图形形式
图={
'a':{'c':3,'e':5},
'c':{'a':3,'d':5},
'd':{'c':3,'e':6},
'e':{'d':6,'a':5}
}
#定义功能
def dijkstra(图表、开始、目标):
最短距离={}空字典
predecesor={}#空字典
unseen_nodes=图形#使其贯穿整个过程,直到看到所有节点
路径=[]
#从开始节点到下一个节点
打印(str(“hi”))
对于不可见节点中的节点:
最短距离[节点]=999999
最短距离[起点]=0
打印(最短距离)
#强壮的迪杰克斯特拉斯向他抛媚眼
不可见的_节点时:
最小节点=无
对于不可见节点中的节点:
如果最小节点为无:
最小节点=节点
elif最短距离[节点]<最短距离[最小节点]:
最小节点=节点
对于childNode,在图[min_node]中指定权重。项()
如果权重+最短距离[最小节点]<最短距离[子节点]:
最短距离[子节点]=权重+最短距离[最小节点]
predecesor[childNode]=最小节点
不可见的节点。pop(最小节点)
打印(最短距离)
#跟踪路径的反向堆栈方法
当前节点=目标
当前_节点时!=开始:
尝试:
插入路径(0,当前_节点)
当前_节点=predecesor[当前_节点]
除KeyError外:
打印('路径无效')
#中断
路径.插入(0,开始)
如果最短距离[目标]!=math.inf:
#打印(目标)
打印('最短距离为'+str(最短距离[目标]))
打印('路径为'+str(路径))
其他:
打印(“出了问题!”)
如果_uname _=='_u main __':#仅当脚本
dijkstra(图'a','d')

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

shortest_distance = {} #empty dictionary
predeccesor = {} #empty dictionary 
unseenNodes = graph #makes it run through til all are seen
path = []
您定义的第二个函数,init()是一个类方法,您不能在类之外定义它


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

您只需要一个更改

  • 从代码中删除
    def\uuuu init\uuuuu(self):函数
  • \uuuu init\uuuu函数用于初始化 对象的变量

  • 您不能调用
    \uuuu init\uuuu
    函数,这就是您没有得到任何输出的原因

  • 也做适当的缩进你会得到你的输出
\uuuu init\uuuu()
从未被调用\uuuu init\uuuu是类构造函数(类似),但这些都是顶级函数,您没有将
\uuuu init\uuuu
放在类中
dijkstra()
什么都不做,它所做的只是设置一些局部变量,这些变量在退出时被销毁。你的缩进也全错了。我把这个复制成了pycharm