简体   繁体   中英

Recursive Python function returning PowerSet of items

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

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.

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

I found this solution on the internet:

def powset3(seq):
    if seq:
        p = powset3(seq[1:])
        return p + [x + seq[:1] for x in p]
    else:
        return [[]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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