簡體   English   中英

遞歸和附加到列表

[英]Recursion and appending to lists

我遇到程序問題,程序只需一個單詞,一次更改一個字母,將該單詞轉換為目標單詞。 雖然,請記住,根據我給出的單詞詞典,轉換后的單詞必須是合法的單詞。

我無法弄清楚如何使其遞歸。 該程序對必須采取的步驟數量有限制。

輸出需要是一個列表。 因此,如果函數更改的參數是
改變(“發現”,“失敗”),輸出應該是:['找','好','行','孤獨','失去']。

用我當前的代碼:

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時它會給出好的和喜歡的,精細的是以目標詞結束的那個,並且喜歡失敗,但是我不知道如果我追加了它就該如何擺脫它它到持有人名單。

任何幫助,將不勝感激。

干杯。

如果您嘗試將列表添加到列表中,則可能需要extend而不是append

http://docs.python.org/library/stdtypes.html#mutable-sequence-types

我並不完全相信使用extend而不是append可以解決你所有的問題,因為看起來這可能無法解決那些不會導致解決問題並需要回溯的改變。

如果事實證明我是正確的,其他答案不會結束,這里有一個遞歸函數,可以將您當前的結果轉換為您要查找的內容:

def flatten_result(nested_list, target):
    if not nested_list:
        return None
    for word, children in zip(nested_list[::2], nested_list[1::2]):
        if word == target:
            return [word]
        children_result = flatten_result(children, target)
        if children_result:
            return [word] + children_result
    return None

>>> result = ['fine', ['line', ['lone', ['lose', []]]], 'fond', []]
>>> flatten_result(result, 'lose')
['fine', 'line', 'lone', 'lose']

這是另一種實現方式。 它不使用遞歸,而是使用排列。 它被重寫為通過wordlist而不是依賴於全局wordlist,這應該使它更便攜。 此實現也嚴格依賴於生成器,這確保了比擴展列表更小的內存占用(如擴展/追加解決方案中)

import itertools

somelists = [['find','fine','line','lone','lose'],
            ['bank','hank','hark','lark','lurk'],
            ['tank','sank','sink','sing','ding']]

def changeling(word, target, wordlist):
    def difference(word, target):
        return len([i for i in xrange(len(word)) if word[i] != target[i]])

    for length in xrange(1, len(wordlist) + 1):
        for possibilities in [j for j in itertools.permutations(wordlist, length) if j[0] is word and j[-1] is target]:
            #computes all permutations and discards those whose initial word and target word don't match parameters
            if all(difference(possibilities[i], possibilities[i+1]) == 1 for i in xrange(0, len(possibilities) - 1)):
                #checks that all words are exactly one character different from previous link
                return possibilities
                #returns first result that is valid; this can be changed to yield if you wish to have all results

for w in somelists:
    print "from '%s' to '%s' using only %s" % (w[-2], w[0], w)
    print changeling(w[-2], w[0], w)
    print 

w[-2], w[0]可以修改/替換以匹配您選擇的任何單詞

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM