1

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
3
  • What issues are you running into? Also, you don't have to call getAllSubsets twice; call it once and save the result. Commented Sep 4, 2015 at 21:44
  • 1
    What are the issues? Commented Sep 4, 2015 at 21:45
  • It just keeps recursing until it returns empty lists all the way back up again. Commented Sep 4, 2015 at 21:50

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.