hi i already looked throw the forum but didn't found solution to my problem. the problem is : how can i find all the possible subsets [that are of length l] of list in S size . and return it in a list.
Asked
Active
Viewed 148 times
0
-
1Look for the powerset recipe in [itertools](http://docs.python.org/2/library/itertools.html). – kojiro Jan 16 '14 at 14:38
-
3[`itertools.combinations`](http://docs.python.org/2/library/itertools.html#itertools.combinations) – thefourtheye Jan 16 '14 at 14:38
-
I'm sure this is a duplicate. – kkuilla Jan 16 '14 at 14:40
-
^^ The python documentation is the first place you should go. – Joel Cornett Jan 16 '14 at 14:40
-
http://stackoverflow.com/a/18155089/2545927 might do it – kkuilla Jan 16 '14 at 14:43
-
2possible duplicate of [Generate all possible permutations of subsets containing all the element of a set](http://stackoverflow.com/questions/18154860/generate-all-possible-permutations-of-subsets-containing-all-the-element-of-a-se) – llrs Jan 16 '14 at 14:50
1 Answers
1
In [162]: x=[1,2,3]
...: from itertools import combinations
...: print [subset for i in range(len(x)+1) for subset in combinations(x, i)]
#outputs: [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
to do that without combinations:
In [237]: import numpy as np
...: x=np.array([1,2,3])
...: n=2**len(x)
...: res=[]
...: for i in range(0, n):
...: mask='{0:b}'.format(i).zfill(len(x))
...: mask=np.array([int(idx) for idx in mask], bool)
...: res.append(x[mask].tolist())
...: print res
#output: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]

zhangxaochen
- 32,744
- 15
- 77
- 108
-
thank you ! but there is another way for doing it without combinations? – guffi8 Jan 16 '14 at 18:26