简体   繁体   English

存储递归函数的输出

[英]Store output of a recursive function

I wrote a recursive function to get all the possible combinations of a given list. 我编写了一个递归函数来获取给定列表的所有可能组合。 Below is the code. 下面是代码。

It takes a list argument and prints all possible combinations. 它使用一个列表参数并打印所有可能的组合。

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)

So If we call getCombinations([1,2,3]) , it prints as below: 因此,如果我们调用getCombinations([1,2,3]) ,则输出如下:

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

My question is how do I store the above result in a list. 我的问题是如何将以上结果存储在列表中。 I have tried to look for solution, and I know the issue is function doesn't technically return anything, but even if I try replacing return with print(...) it doesn't work as expected and returns nothing. 我试图寻找解决方案,并且我知道问题是函数从技术上讲不会返回任何内容,但是即使我尝试用print(...)替换return也不起作用,也不会返回任何内容。

There's many ways to do this, but starting from your code, it's probably easiest to turn your function into a generator. 有很多方法可以执行此操作,但是从代码开始,将函数转换为生成器可能是最简单的。

A generator doesn't return the whole result in one go, but each element as it becomes available. 生成器不会一次返回整个结果,而是在每个元素可用时返回。 That way, you can replace your print with a yield and collect everything in a single list by wrapping the call to helper(a,ans,0) in a list() . 这样,您可以将print替换为yield并通过将对helper(a,ans,0)的调用包装在list() ,将所有内容收集在一个list()

However, since your code modifies the existing answer, you need to collect copies of the list, not the list itself, since that will change in later iterations. 但是,由于您的代码修改了现有答案,因此您需要收集列表的副本,而不是列表本身,因为这将在以后的迭代中更改。

So: 所以:

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]))

It's a very complicated way to do this though and very messy with the empty strings - why not use the standard libraries: 但是,这是一种非常复杂的方法,而且对于空字符串也很混乱-为什么不使用标准库:

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

Or, more generically, for any list: 或者,更笼统地说,对于任何列表:

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]))

You can use a function that extracts the first item from the given list and concatenate it with each of the combinations returned by a recursive call with the rest of the list, until the list becomes empty: 您可以使用一个函数,该函数从给定列表中提取第一项,并将其与递归调用返回的每个组合与列表的其余部分连接起来,直到列表变为空:

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

so that list(getCombinations([1, 2, 3])) returns: 这样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