I am trying to write a program where a shortest path is found between nodes in a list such as the one below. The nodes are A, B, C, D and the path length between them is listed as "A|B|1" or "B|D|9". The program is supposed to iterate through the paths and find the shortest path from first to last node, if the path exists. The part where I'm stuck is the very last for
statement of the code (even though this code is not final and I still need to work on it). This last "for" statement crashes my python shell and then I have to restart it. Maybe an infinite loop?
In this statement I am trying to compare values in the dictionary i created to values to the nextpath
variable which is continuously updated with values from the dictionary. For example if AB is in nextpath
, it should be compared to other values in the dictionary (eg: BD) and since AB contains B, this path can link to BD. The problem is when I try to do this the program crashes and i=I'm stuck.
# input given to code "4","A","B","C","D","A|B|1","B|D|9","B|C|3","C|D|4"
import re
def WeightedPath(strarr):
exclude2=[',','"',"|"]
strarr=list(s for s in strarr if s not in exclude2)
numnodes = int(strarr[0])+1
actualnodes=strarr[1:int(strarr[0])+1]
end = len(strarr)
print "____________________________________________________"
paths = strarr[numnodes:end]
paths2=""
for i in paths:
paths2+=i
paths3=re.split('(\d+)',paths2)
paths3=paths3[0:-1] #last item was empty quotes so i got rid of it
print "paths",paths3
paths_2=[] # second item behind weight
paths_1=[] # first item behind weight
pathsnum=[] # actual weight of path
for i in paths3:
if i.isdigit() == True:
paths_2.append(paths3[paths3.index(i)-2])
paths_1.append(paths3[paths3.index(i)-1])
pathsnum.append(paths3[paths3.index(i)])
dictname=paths3[0::2] #names of dict items
dictionary=dict(zip(dictname,pathsnum))
print "names of nodes: ",actualnodes
print "dictionary: ",dictionary
fromnode= actualnodes[0]
tonode= actualnodes[-1]
tohere=[]
for i in dictionary.keys():
if tonode in i:
tohere.append(i)
nextpath=[]
for i in dictionary.keys():
if fromnode in i:
nextpath.append(i)
for i in dictionary.keys():
if i not in nextpath:
for j in nextpath:
if j[0] in i or j[1] in i:
nextpath.append(i)
print "nextpath",nextpath
print WeightedPath(raw_input())
Aucun commentaire:
Enregistrer un commentaire