我对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')
你只需要一次改变
def __init__(self): function
。在类中使用初始化函数来初始化 对象变量。
不能调用
__init__
函数,这就是为什么没有得到任何输出。好的,所以我修复了一堆代码的缩进、作用域和名称问题(见下文),得到了以下错误
也许这能帮你继续吗?在
^{pr2}$dijkstra函数只执行这四行代码,因为在定义第二个函数之前,它们是惟一的代码行。因此,当您最后调用此函数时,程序会创建一些空字典,然后关闭:
您定义的第二个函数,init()是一个类方法,不能在类之外定义它。在
先看看python中的一些更基本的算法,然后熟悉语法(我不知道它与C有多大的不同)。在
相关问题 更多 >
编程相关推荐