+ 2
What is the code to return all possible subsets of an array using python??
4 Answers
+ 1
But how can it be implemented without using built in functions?
+ 1
I'm assuming that you mean "list" instead of array.... :)
If you want all subsets of length 3:
import itertools
mylist = [1,2,3,4,5]
for subset in itertools.combinations(mylist,3):
print(subset)
If you want all possible subsets (the so-called "powerset"):
import itertools
mylist = [1,2,3,4,5]
for subset_size in range(len(mylist)):
for subset in itertools.combinations(mylist,subset_size+1):
print(subset)
+ 1
First, a question - why? Why reinvent the wheel when you already have (probably much better optimized) code that does it?
As for the answer - I think the easiest way to do it is recursively (at each step, try and select another one of the remaining elements in the list, until you reach a predefined length).
+ 1
And if the answer to my "why" is "because my homework requires me not to use any built-in functions", you're in the wrong place.... :)