1

I am writing a program to return a set of subset of number. For example: list = [1,2,3] my desired function will return [[], [1], [2], [2,1], [3], [3,1], [3,2], [3,2,1]] However, it returns [[], [1], [2], [3]] Here is my code

# Write a powerSet function
def powerSet(list):
    if len(list) == 0:
        return [[]];
    else:
        temp = list.pop()
    return powerSet(list) + [[temp] + x for x in powerSet(list)];

list = [1,2,3];
print(powerSet(list));
1
  • list is a built-in, hence a poor choice for a variable name. Also -- pop() destructively mutates the passed list -- you should be modifying copies of it. Commented Feb 8, 2017 at 4:56

2 Answers 2

2

The problem is that you mutate the list object, so the two powerSet in the last line will not receive the same list (for example, in the first call, the first powerSet will get [1,2] but the second one will get [1]).

The solution is to copy the list when passing it down:

powerSet(list[:]) + [[temp] + x for x in powerSet(list[:])]
Sign up to request clarification or add additional context in comments.

Comments

1

There is a built-in package for "subset"

import itertools

def subset(x):
    all_list = []
    for i in range(len(x)+1):
        all_list+=list(itertools.combinations(x,i))
    return all_list

print subset([1,2,3])
[output>>>] [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

3 Comments

Thank you; however, I think there is another way to solve this problem, but I will have to go from the beginning of the set instead of the end
def p(l):if len(l) == 0: return [[]] #print(p(l[1:]) + [[l[0]] + x for x in p(l[1:])]) return p(l[1:]) + [[l[0]] + x for x in p(l[1:])] s = [1,2,3] print(p(s));
Recursion is not easy to understand I think.. So thank you for the opportunity to study it. By the way, it is interesting to use "yield" and we can learn how python implement permutation and combination from docs.python.org/2/library/itertools.html#itertools.combinations

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.