문제

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.

도움이 되었습니까?

해결책

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]]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top