Search code examples
pythonmathprobability

How to get an array of all possible binary numbers given a binary number of the same length


  • goal: I have a string which usually looks like this "010" and I need to replace the zeros by 1 in all the possible ways like this ["010", "110", "111", "011"]

  • problem when I replace the zeros with 1s I iterate through the letters of the string from left to right then from right to left. As you can see in the code where I did number = number[::-1]. Now, this method does not actually cover all the possibilities.

  • I also need to maybe start from the middle or maybe use the permutation method But not sure how to apply in python.

    • mathematically there is something like factorial of the number of places/(2)!
A = '0111011110000'
B = '010101'
C = '10000010000001101'
my_list = [A,B,C]
for number in [A,B,C]:
    number = number[::-1]
    for i , n in enumerate(number):
        number = list(number)
        number[i] = '1'
        number = ''.join(number)
        if number not in my_list: my_list.append(number)


for number in [A,B,C]:
    for i , n in enumerate(number):
        number = list(number)
        number[i] = '1'
        number = ''.join(number)
        if number not in my_list: my_list.append(number)
print(len(my_list))
print(my_list)


Solution

  • You can use separate out the zeros and then use itertools.product -

    from itertools import product
    x = '0011'
    perm_elements = [('0', '1') if digit == '0' else ('1', ) for digit in x]
    print([''.join(x) for x in product(*perm_elements)])
    ['0011', '0111', '1011', '1111']
    

    If you only need the number of such combinations, and not the list itself - that should just be 2 ** x.count('0')