pythonarrayscombinations

How do I compute all possibilities for an array of numbers/bits (in python, or any language for that matter)


I have been wracking my brains out for 3 hours straight, but I still don't get it, so I am asking here. (I wrote Python in the title, but this could be for pretty much any language)

Let's assume I have an array of bits (but it may also be integers in a defined range) of fixed length n, let's say 5.

array=[0,1,1,0,0]

Now, how do I generate ALL arrays, which are possible in the number range (in the case of bits, 2).

So:

[0,0,0,0,0], [0,0,0,0,1], [0,0,0,1,0], [0,0,0,1,1] ...

I have tried searching for a solution here, but I always find something which is similar, but which doesn't quite solve my problem.

To solve this, I have tried various loops, but I always end up either getting one possibility more than once (should not happen), or not getting all possible ones.

I can manage to do this with if statements (to check if a combination already exists), but that seems very unsophisticated.

Is there a simple method, using only loops, to obtain all possibilities?

Thank you

Edit: Since this was mentioned below, no, this is not homework. This is for research in order to implement a Bayesian network of binary states. (on/off).


Solution

  • In Python, use itertools for stuff like this

    from itertools import product
    for i in product([0,1], repeat=5): 
        print(i)
    

    Yields:

    (0, 0, 0, 0, 0)
    (0, 0, 0, 0, 1)
    (0, 0, 0, 1, 0)
    (0, 0, 0, 1, 1)
    (0, 0, 1, 0, 0)
    etc...