How to get a the number of all possible combinations?

0

Issue

  • goal: I have a string usually look 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')

Answered By – Mortz

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More