Recursive Python function returning PowerSet of it

2019-08-14 19:12发布

问题:

I'm trying to debug a program and am running into issues. Can anybody direct me to the issue here?

The program is meant to take a list of items, and returns the list of powersets for those items.

An example:

>>> getAllSubsets([1,2])
[[1,2],[1],[2],[]]

The code:

def getAllSubsets(lst):
    if not lst:
        return []
    withFirst = [ [lst[0]] + rest for rest in getAllSubsets(lst[1:]) ]
    withoutFirst = getAllSubsets(lst[1:])
    return withFirst + withoutFirst

回答1:

There are better recipes, yes. But I think the problem with your code is that you should replace return [] with return [[]]. The empty set is itself a subset.



回答2:

There's a powerset generator in the recipes section of the itertools documentation; you should use that.

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))