【问题标题】:Recursion and appending to lists递归和追加到列表
【发布时间】:2012-04-10 05:45:36
【问题描述】:

我在使用某个程序时遇到问题,该程序需要一个单词,一次更改一个字母,然后将该单词转换为目标单词。不过,请记住,根据我得到的词典,转换后的词必须是合法词。

我无法弄清楚如何使其递归。该程序对其必须执行的步骤数量有限制。

输出需要是一个列表。因此,如果函数更改的参数是
changeling("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

我收到一个混乱的输出: ['fine', ['line', ['lone', ['lose', []]]], '喜欢', []]

我得到了我想要的答案,但我不确定如何 a) 清理它,因为列表中没有列表。和 b) 喜欢出现,因为当 find 被调用时,它给出了很好和喜欢,罚款是以目标词结尾的那个,喜欢失败,但我不知道一旦我附加了如何摆脱它它到持有人名单。

任何帮助将不胜感激。

干杯。

【问题讨论】:

  • 回复您现在已删除的问题:尝试找到一个对您有用的程序(比如检索一些天气数据或新闻,或者计算您的打字速度或其他什么的程序)并对其进行编程.保持简单开始,然后添加一些东西。

标签: python list loops recursion append


【解决方案1】:

这是另一种实现方式。它不使用递归,而是使用排列。它被重写以传递单词表而不是依赖于全局单词表,这应该使它更便携。这种实现也严格依赖于生成器,这确保了比扩展列表更小的内存占用(如在扩展/追加解决方案中)

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] 可以修改/替换以匹配您选择的任何单词

【讨论】:

    【解决方案2】:

    我不完全相信使用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']
    

    【讨论】:

    • 我不确定如何在 changeling 中实现这个程序。我可以在 python shell 中使用它,它可以工作,但是考虑到换行是递归的,所以出了问题,我得到了原始输出。
    • 另外,你知道如何让输出包含 changeling 的第一个单词吗?我可以将 changeling 更改为拥有 holderlist=[word],但随后我得到一大堆重复项.
    【解决方案3】:

    如果您尝试将列表添加到列表中,您可能需要extend 而不是append

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

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 2017-12-15
      • 1970-01-01
      • 2012-04-11
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      相关资源
      最近更新 更多