0

I'm looking for a way to generate all possible binary combinations in a list. For example, if I have 5 spaces available, I would like to create a list that contains all the possible combinations from ["00000", ..., "11111"], I don't know if I have explained myself well, I found here some similar questions but I managed to implement it as I am looking for ...

indexNames = ["00000", "00001", "00010", ..., "11111"]

If n = 5.

indexNames = ["00", "01", "10", "11"]

If n = 2.

Frostman
  • 53
  • 1
  • 7

1 Answers1

0

You should use itertools.product

Roughly equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B)

The nested loops cycle like an odometer with the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order.

from itertools import product  

def get_binary(length):
    perm=product(['0', '1'], repeat=length)
    possible_bin=[]
    for i in list(perm):  
        my_bin=''.join(i) 
        possible_bin.append(my_bin)
    return possible_bin
  
print(get_binary(3))
print(get_binary(4))
print(get_binary(5))
['000', '001', '010', '011', '100', '101', '110', '111']
['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']
['00000', '00001', '00010', '00011', '00100', '00101', '00110', '00111', '01000', '01001', '01010', '01011', '01100', '01101', '01110', '01111', '10000', '10001', '10010', '10011', '10100', '10101', '10110', '10111', '11000', '11001', '11010', '11011', '11100', '11101', '11110', '11111']
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22