Search code examples
pythoncombinationspermutation

How to determine all the possible combinations given a list of binary numbers (0s or 1s or None) of length n?


I want to write a function in order to determine all the possible combinationsf of a list of length n given binary numbers (0s or 1s or None).

Lets say my list should have a length of 3. Than the desired output should be:

arrangement_1 = [0,0,0]
arrangement_2 = [1,0,0]
arrangement_3 = [0,1,0]
arrangement_4 = [0,0,1]
arrangement_5 = [1,1,0]
arrangement_6 = [1,0,1]
arrangement_7 = [0,1,1]
arrangement_8 = [1,1,1]
arrangement_9 = [0,0,None]
arrangement_10 = [None,0,0]
arrangement_11 = [0,None,0]
arrangement_12 = [0,None,None]
arrangement_13 = [None,0,None]
arrangement_14 = [None,None,0]
arrangement_15 = [1,1,None]
arrangement_16 = [None,1,1]
arrangement_17 = [1,None,1]
arrangement_18 = [1,None,None]
arrangement_19 = [None,1,None]
arrangement_20 = [None,None,1]
arrangement_21 = [None,1,0]
arrangement_N  = [...]

I tried the following function by giving it a random initial state of 1s/0s and None elements, but it is not giving me the desired output (i also tried other functions like combinations - also no desired output):

def calc_permutations(list = []): # Takes list with n elements and calculates no of permutations and return dictionary of number of permutations and states

    possible_states = [] 

    for i in permutations(list,len(list)):
        possible_states.append(i)

    possible_states = {"noOfstates": len(possible_states), "states": possible_states} 
    return possible_states 

Solution

  • You can use itertools.product:

    from itertools import product
    alphabet = [0, 1, None]
    for x in product(alphabet, repeat=3):
      print(x)
    

    Output:

    (0, 0, 0)
    (0, 0, 1)
    (0, 0, None)
    (0, 1, 0)
    (0, 1, 1)
    (0, 1, None)
    (0, None, 0)
    (0, None, 1)
    (0, None, None)
    (1, 0, 0)
    (1, 0, 1)
    (1, 0, None)
    (1, 1, 0)
    (1, 1, 1)
    (1, 1, None)
    (1, None, 0)
    (1, None, 1)
    (1, None, None)
    (None, 0, 0)
    (None, 0, 1)
    (None, 0, None)
    (None, 1, 0)
    (None, 1, 1)
    (None, 1, None)
    (None, None, 0)
    (None, None, 1)
    (None, None, None)