Skip to content Skip to sidebar Skip to footer

I Am Stuck With Recursion In Power Set Using Python

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, i

Solution 1:

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

Solution 2:

There is a built-in package for "subset"

import itertools

defsubset(x):
    all_list = []
    for i inrange(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)]

Post a Comment for "I Am Stuck With Recursion In Power Set Using Python"