I have copied and pasted this answer for Dijkstra Algorithm to my project. It seemed ok after several simple tests.
In my specific implementation, I need the algorithm to return a list of nodes. So I have to modify the original code so that it always returns a list. More specifically, I removed all the return "string" lines there. The modified code by me is as follows:
## using Dijkstra Algorithm ##
def choosePath(s, t):
net = {'0':{'1':138, '9':150},
'1':{'0':138, '2':178, '8':194},
'2':{'1':178, '3':47.5},
'3':{'2':47.5, '4':70},
'4':{'3':70, '5':70},
'5':{'4':70, '6':36},
'6':{'5':36, '7':50},
'7':{'6':50, '8':81},
'8':{'7':81, '9':138, '1':194},
'9':{'8':138, '0':150}}
# sanity check
if s == t:
return []
# create a labels dictionary
labels={}
# record whether a label was updated
order={}
# populate an initial labels dictionary
for i in net.keys():
if i == s: labels[i] = 0 # shortest distance form s to s is 0
else: labels[i] = float("inf") # initial labels are infinity
from copy import copy
drop1 = copy(labels) # used for looping
## begin algorithm
while len(drop1) > 0:
# find the key with the lowest label
minNode = min(drop1, key = drop1.get) #minNode is the node with the smallest label
# update labels for nodes that are connected to minNode
for i in net[minNode]:
if labels[i] > (labels[minNode] + net[minNode][i]):
labels[i] = labels[minNode] + net[minNode][i]
drop1[i] = labels[minNode] + net[minNode][i]
order[i] = minNode
del drop1[minNode] # once a node has been visited, it's excluded from drop1
## end algorithm
# print shortest path
temp = copy(t)
rpath = []
path = []
while 1:
rpath.append(temp)
if order.has_key(temp):
temp = order[temp]
if temp == s:
rpath.append(temp)
break
for j in range(len(rpath)-1,-1,-1):
path.append(rpath[j])
return [junctions[int(elem)] for elem in path]
Then when I run it, I end up with the following error:
>>> Traceback (most recent call last):
File "C:\Users\...\simulation.py", line 162, in choosePath
rpath.append(temp)
MemoryError
Obviously, it is because I have removed the return "string" lines. However, I failed to find out which deletion makes it die. Why is it so?
How may I make it work again AND always returns a list instead of a string as I wish?
rpathuntil you run out of memory. I'm not sure why that's happening, but perhaps you could add code to catch the exception if it happens and print outrpathand theorderdictionary? That should give you a good idea of what's going wrong.