I have a list (containing only the numbers 0 or 1) with a quantity X of 0, for example 4:
[0,0,0,0]
And I need to find all possible combinations with these numbers, that is:
[1,0,0,0], [0,1,0,0], [0,0,1,0], [1,1,0,0] ........ [1,1,1,1]
But that's a lot of combinations, so I'm not sure which method to use.
I have consulted a method called Bitmask which can solve the problem, I tried to do it with a nested for but it was not possible.
Is there a practical way or algorithm for this problem?
The canonical answer would be to use
itertools.product
, as you have already been told in a comment.However, just out of curiosity , I couldn't help but implement this other solution, taking advantage of the fact that deep down all those combinations of zeros and ones you're generating can be read as the binary encoding of all numbers between 0 and 2* *X (being
X
the number of "bits" you are considering, in your case four).I insist that it is nothing more than a curiosity. This version is about 30 times slower than using
itertools.product
.The most basic way as long as the amount of
0
y1
is bounded could be by doing a list comprehension, something like this:But ultimately the above is nothing more than a Cartesian product with repetitions that you could solve natively with
itertools.product()
as follows:Important:
Both solutions deliver an iterator, so it is necessary to convert them to a list to, for example, print the values, but you have to be careful with this, since it is very easy when we work with combinations, permutations or Cartesian products that the elements generated are skyrocketing in quantity, materializing the result in a list or another object could claim the available memory and more, not to mention the time needed to do it.