I am trying to figure out how to do this in Python:
Print out all subsets of any given set.
For example: [1,2]
So the answer is by hand the following:
[]
[2]
[1]
[1,2]
I realized that the total number of solutions would be 2(exp)n
, where n
is the number of elements in the list.
So for example, if the list is [1,3,4]
, then the total number of subsets would be 2(exp)3 = 8
.
I also realized that if I got the binary bit representation of the list above, the following appears:
So for example: [1,2]
00 : []
01 : [2]
10 : [1]
11 : [1,2]
Each position of the bit that contains a 1
, that is the position of the subset when indexing it to the original set [1,2]
. eg binary 01 = get index at position 1 of the original set [1,2]
which would be [2]
.
Binary 11, means get index positions 0 and 1 from the original set [1,2]
which gives an answer of [1,2]
, etc.
How can I code this, the code I have is so messy, is there a easy way to map this?