Python递归和变量范围

时间:2016-05-21 05:41:23

标签: python recursion reference

我正试图弄清楚这个LeetCode问题Palindrome Partitioning的解决方案。这就是我目前所拥有的:

def partition(s):
    out = []
    def isPalindrome(word):
        return word == word[::-1]

    def addPalindrome(word, start, partition):
        if start == len(word):
            out.append(partition)  #where I append to 'out'
            print out, partition  # where I print the finished partition
            return
        for i in range(start+1, len(word)+1):
            sub = word[start:i]
            if isPalindrome(sub):
                partition.append(sub)
                addPalindrome(word, i, partition)
                partition.pop()

    if not s:
        return []
    addPalindrome(s, 0, [])
    return out

print partition('aaa')

输入'aaa'的正确解决方案是[['a', 'a', 'a'], ['a', 'aa'], ['aa', 'a'], ['aaa']]。当我在基本情况下打印partition时,它似乎是正确的。我将它们附加到out变量,该变量应该超出递归范围并正确返回。

但事实并非如此。我不明白为什么在基本情况下打印out会导致这个:

[['a', 'a', 'a']]
[['a', 'aa'], ['a', 'aa']]
[['aa', 'a'], ['aa', 'a'], ['aa', 'a']]
[['aaa'], ['aaa'], ['aaa'], ['aaa']]

最后,当返回out时,它似乎返回空数组。这里发生了什么?

递归后out的输出为[[], [], [], []]

这是Python2.7

1 个答案:

答案 0 :(得分:0)

我看到的问题是1)记住要复制保存(如评论中所述)和2)使用全局来保存增长结果而不是在递归中处理。让我们简化代码并修复这两个问题:

def isPalindrome(word):
    return word == word[::-1]

def addPalindrome(word, start, partitions):
    result = []

    if start == len(word):
        result.append(list(partitions))  # where I append to 'out'
    else:
        for i in range(start+1, len(word)+1):
            sub = word[start:i]

            if isPalindrome(sub):
                partitions.append(sub)
                result.extend(addPalindrome(word, i, partitions))
                partitions.pop()
    return result

def partition(s):
    out = []

    if s:
        out = addPalindrome(s, 0, [])

    return out

print partition('aaa')

在递归中而不是作为全局递归结果时,关键是知道何时到*.append()以及何时到*.extend()增长的结果。