I am trying to create a recursive function that returns the set of all non-empty subset of [1,2,3,...,n]
numbers.
Here is my code:
def subsets(n):
if n == 2:
return ([1], [2], [1, 2])
else:
previous = subsets(n - 1)
temp = previous
result = ()
for set in previous:
set += [n]
result += (set,)
return temp + ([n],) + result
this doesn't work as temp
stores the value of previous
after it has been modified. Simply changing it to-
previous = subsets(n - 1)
temp = subsets(n - 1)
works but is obviously not a very efficient solution. I have also tried-
previous,temp = subsets(n - 1)
but this raises a "too many values to unpack" error. What do I do?