Lets first explain the idea,
For each subset, it can contain 0 to length(N) item.
So, We can do the followings for L= [1,2,3,4]
- First one, []
- Pick only one element. i.e [1], [2], [3], [4]
- Pick two elemens [1,2], [2,3], [3,4].
- Pick three and so on
Now how can we do this programmatically, so that we consider all the subsets?
We can use a binary number counter. Consider a number as a string, and get the indexes where we have 1
in it. Now only include items from L
for those indexes.
See below example,
000 -> No one, so, a subset = []
001 -> index `0` has one, L[0] = 1, so a subset = [1]
010 -> index `1` has one, L[1] = 2, so a subset = [2]
011 -> index `0`, `1` has one, L[0] = 1 L[1] = 2, so a subset = [1, 2]
100 -> index `2` has one, L[2] = 3, so a subset = [3]
....
This way we get all the subsets.
The above code does the followings,
Populates a list of binary number X
up to 2^n (i.e 2^n is the total subset of an N length list)
X = [format(x, '03b') for x in range(2**len([1,2,3,4]))]
['000', '001', '010', '011', '100', '101', '110', '111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']
Iterate each item on X
list. For each item, iterate over each character and checks if it is 1
. If yes, then include that index item from L
to the result item.
[[L[i] for i in range(len(I)) if I[i]=='1'] for I in X]
This can be easily understandable by,
subsets = []
for I in X:
for i in range(len(I)):
if I[i]=='1':
subsets.append([L[i])