我試圖編寫一個程序,其中在下面的列表中的節點之間找到最短路徑。節點是A,B,C,D,它們之間的路徑長度被列爲「A | B | 1」或「B | D | 9」。如果路徑存在,該程序應該遍歷路徑並找到從第一個節點到最後一個節點的最短路徑。我卡住的部分是代碼的最後一個for
聲明(儘管此代碼不是最終的,我仍然需要處理它)。這最後的「for」語句崩潰了我的python shell,然後我必須重新啓動它。也許是一個無限循環?使用多個if語句python corectly
在此聲明中,我試圖將我創建的字典中的值與nextpath
變量的值進行比較,該變量使用字典中的值不斷更新。例如,如果AB在nextpath
中,應該將其與字典中的其他值進行比較(例如:BD),並且由於AB包含B,此路徑可以鏈接到BD。問題是當我嘗試做這個程序崩潰,我=我卡住了。
# 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())
爲什麼不把它建模爲圖形並應用dijikstra? – pretobomba
我不熟悉那種方法...我會考慮它 – eni