Create A List Of All The Subsets Of A Given List In Python 3.x
how can I create a list of all the subsets of a given list in python 3.x? the list given be like [1,2,3] and i want an output like [[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3],[]]
Solution 1:
You can use itertools.combinations
to get the combinations:
>>>import itertools>>>xs = [1, 2, 3]>>>itertools.combinations(xs, 2) # returns an iterator
<itertools.combinations object at 0x7f88f838ff48>
>>>list(itertools.combinations(xs, 2)) # yields 2-length subsequences
[(1, 2), (1, 3), (2, 3)]
>>>for i inrange(0, len(xs) + 1): # to get all lengths: 0 to 3...for subset in itertools.combinations(xs, i):...print(list(subset))...
[]
[1]
[2]
[3]
[1, 2]
[1, 3]
[2, 3]
[1, 2, 3]
combining with list comprehension, you will get what you want:
>>> [list(subset) for i in range(0, len(xs) + 1)
for subset in itertools.combinations(xs, i)]
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Solution 2:
The question is really to ask the powerset. Here is another way to generate it: (without the itertools.combinations())
>>> L = [1, 2, 3]
>>> res = [[]]
>>> for e in L:
res += [sub + [e] forsubin res]
>>> res
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
Or you can just use this 3rd party lib more_itertools: powerset (as the name aptly reflects its purpose).
>>>import more_itertools>>>list(more_itertools.powerset(L))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
>>>
Solution 3:
I tried this. without recursion. which worked out successfully.
A is list , K is length of every subset
def subsets(A,K):
sets = []
for j in range(len(A)-K+1):
mySet = []
for i in range(j,K+j):
mySet.append(A[i])
sets.append(mySet)
return sets
Post a Comment for "Create A List Of All The Subsets Of A Given List In Python 3.x"