我遇到了一個程序問題,程序需要一個單詞,並且一次更改一個字母,將該單詞轉換爲目標單詞。雖然,請記住,根據我給出的單詞字典,轉換後的單詞必須是合法的單詞。遞歸和追加到列表
我很難弄清楚如何使它遞歸。該程序對其必須採取的步驟數量有限制。
輸出需要是一個列表。所以如果函數轉換的參數是
轉換(「find」,「lose」),輸出應該是: ['find','fine','line','lone','lose']。
與我當前的代碼:
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)
holderlist.append(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)
holderlist.append(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)
holderlist.append(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)
holderlist.append(changeling(items,target,steps-1))
else:
return None
i+=1
return holderlist
我收到一個混亂的輸出: [ '精',[ '線',[ '孤獨',[ '失去',[]]]],「我喜歡',[]]
我得到了我想要的答案,但我不知道如何a)通過在列表中沒有列表來清理它。和b)喜歡出現,因爲當調用find時它會給人以美好的感覺,那麼罰款就是以目標詞爲結尾的詞,而且喜歡失敗,但我不知道如何在我追加後刪除它它的持有者名單。
任何幫助,將不勝感激。
乾杯。
在回答你現在已經刪除的問題:試着找到一個對你有用的程序(比如說可以檢索一些天氣數據或新聞,或者計算你的打字速度等等)並對它進行編程。保持簡單開始,然後添加一些東西。 – assylias 2012-10-13 07:13:43