繁体   English   中英

存储递归函数的输出

[英]Store output of a recursive function

我编写了一个递归函数来获取给定列表的所有可能组合。 下面是代码。

它使用一个列表参数并打印所有可能的组合。

def getCombinations(a):
    a2 = []
    ans = ['' for i in range(len(a))]
    helper(a,ans,0)

def helper(a,ans,i):
    if i == len(ans):
        print (ans)
    else:
        ans[i] = ''
        helper(a,ans,i+1)
        ans[i] = a[i]
        helper(a,ans,i+1)

因此,如果我们调用getCombinations([1,2,3]) ,则输出如下:

['', '', '']
['', '', 3]
['', 2, '']
['', 2, 3]
[1, '', '']
[1, '', 3]
[1, 2, '']
[1, 2, 3]

我的问题是如何将以上结果存储在列表中。 我试图寻找解决方案,并且我知道问题是函数从技术上讲不会返回任何内容,但是即使我尝试用print(...)替换return也不起作用,也不会返回任何内容。

有很多方法可以执行此操作,但是从代码开始,将函数转换为生成器可能是最简单的。

生成器不会一次返回整个结果,而是在每个元素可用时返回。 这样,您可以将print替换为yield并通过将对helper(a,ans,0)的调用包装在list() ,将所有内容收集在一个list()

但是,由于您的代码修改了现有答案,因此您需要收集列表的副本,而不是列表本身,因为这将在以后的迭代中更改。

所以:

from copy import copy

def getCombinations(a):
    ans = ['' for i in range(len(a))]
    return list(helper(a,ans,0))

def helper(a,ans,i):
    if i == len(ans):
        yield copy(ans)
    else:
        ans[i] = ''
        yield from helper(a,ans,i+1)
        ans[i] = a[i]
        yield from helper(a,ans,i+1)

print(getCombinations([1,2,3]))

但是,这是一种非常复杂的方法,而且对于空字符串也很混乱-为什么不使用标准库:

from itertools import combinations
print([c for n in range(4) for c in combinations([1, 2, 3], n)])

或者,更笼统地说,对于任何列表:

from itertools import combinations
def all_combinations(a):
    return([c for n in range(len(a)+1) for c in combinations(a, n)])
print(all_combinations([1, 2, 3]))

您可以使用一个函数,该函数从给定列表中提取第一项,并将其与递归调用返回的每个组合与列表的其余部分连接起来,直到列表变为空:

def getCombinations(lst):
    if lst:
        first, *rest = lst
        for value in '', first:
            for combination in getCombinations(rest):
                yield [value, *combination]
    else:
        yield []

这样list(getCombinations([1, 2, 3]))返回:

[['', '', ''],
 ['', '', 3],
 ['', 2, ''],
 ['', 2, 3],
 [1, '', ''],
 [1, '', 3],
 [1, 2, ''],
 [1, 2, 3]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM