0
我遇到一個程序有問題,程序需要一個單詞,並且一次更改一個字母,將該單詞轉換爲目標單詞。雖然,請記住,根據我給出的單詞字典,轉換後的單詞必須是合法的單詞。遞歸與列表
我很難弄清楚如何使它遞歸。該程序對其必須採取的步驟數量有限制。
編輯:我不能讓持有人名單全球。
到目前爲止我的代碼:
def changeling(word,target,steps):
holderlist=[]
i=0
if steps<0 and word!=target:
return None
if steps!=-1:
for items in wordList:
if len(items)==len(word):
i=0
if items!=word:
for length in items:
if i==1:
if items[1]==target[1] and items[0]==word[0] and items[2:]==word[2:]:
if items==target:
print "Target Achieved"
holder.list.append(target)
holderlist.append(items)
changeling(items,target,steps-1)
elif i>0 and i<len(word)-1 and i!=1:
if items[i]==target[i] and items[0:i]==word[0:i] and items[i+1:]==word[i+1:]:
if items==target:
print "Target Achieved"
holderlist.append(items)
changeling(items,target,steps-1)
elif i==0:
if items[0]==target[0] and items[1:]==word[1:]:
if items==target:
print "Target Achieved"
holderlist.append(items)
changeling(items,target,steps-1)
elif i==len(word)-1:
if items[len(word)-1]==target[len(word)-1] and items[0:len(word)-1]==word[0:len(word)-1]:
if items==target:
print "Target Achieved"
holderlist.append(items)
changeling(items,target,steps-1)
else:
changeling(None,None,steps-1)
i+=1
return holderlist
我最大的問題是,我的控股名單holderlist刷新每次我嘗試讓程序遞歸。
我可以解決它,如果我手動輸入數據。這是我想要的程序來做:
changeling("find","lose",4)
gives me:
['fine','fond']
the program should then do:
changeling('fine','lose',3)
gives me:
['line']
changeling('line','lose',2)
gives me:
['lone']
changeling('lone','lose',1)
gives me:
['lose']
Target Achieved
現在已經晚了這裏,而且我不打算現在看這個節目。但事實上,你已經將它嵌入了九層深,這是一個強有力的指標,表明存在根本性錯誤。 – 2012-03-21 21:20:01
恩,感謝您的意見。 – Unknown 2012-03-21 21:23:56
就像一個想法:做'如果步驟!= -1:<長縮進塊>',而不是'如果步驟== -1:返回holderlist',然後放置之前的縮進塊(保存一個縮進) 。類似的,不是'如果項目!=單詞:<長縮進塊>',做'if items == word:break';使用這種策略,您可以輕鬆減少到三個/四個嵌套層次,讓您實際可視化程序的邏輯流程。另外,是不是'holder.list.append(target)'一個錯字? – 2012-03-21 21:33:48