+ 2

What is the code to return all possible subsets of an array using python??

20th Jun 2017, 8:05 AM
Palaghat Yaswanth Sai
Palaghat Yaswanth Sai - avatar
4 Respostas
+ 1
But how can it be implemented without using built in functions?
21st Jun 2017, 6:53 AM
Palaghat Yaswanth Sai
Palaghat Yaswanth Sai - avatar
+ 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)
20th Jun 2017, 12:53 PM
Bogdan Sass
Bogdan Sass - avatar
+ 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).
21st Jun 2017, 7:01 AM
Bogdan Sass
Bogdan Sass - avatar
+ 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.... :)
21st Jun 2017, 7:06 AM
Bogdan Sass
Bogdan Sass - avatar