I have the following sequence with missing 1s and 0s:
"01010xx101xxx001"
And I need to print all possible sequences instead of the missing places marked by "x"
How can I do it if I might also need to change the number of "x"
s?
CodePudding user response:
You can do the following, using itertools.product
:
from itertools import product
def combs(string):
for p in map(iter, product("01", repeat=string.count("x"))):
yield "".join(c if c in "01" else next(p) for c in string)
# maybe more consistent:
# yield "".join(next(p) if c == "x" else c for c in string)
for c in combs("01010xx101xxx001"):
print(c)
0101000101000001
0101000101001001
0101000101010001
0101000101011001
0101000101100001
0101000101101001
# ...
Some documentation on the utils used here:
CodePudding user response:
There's already a pretty good answer, and I suggest you study it. Here's another solution that I think walks you a bit more through each step:
l = '1010xx101xxx001'
# count x's
count = len([c for c in l if c == 'x'])
# There will be 2 ^ {count} combinations, so iterate from 0 to 2 ^ {count} - 1
for i in range(2 ** count):
# Get the binary representation of i
b = str(bin(i)).replace('0b', '')
# Pad with zero's so we get {count} digits ('1' becomes '00001')
b_p = '0' * (count - len(b)) b
# Replace x's one at a time
out = l
for digit in b_p:
out = out.replace('x', digit, 1)
print(out)