I'm currently working on a problem that requires I design a function that takes a string of '0's, '1's, and 'X's as an argument and returns a generator which yields the different combinations of the X's turned to 1's and 0's
ie: passing '0XX1', would return a generator that yields-> 0001, 0101, 0011, 0111,
I have solved the problem iteratively, but need to be able to able to solve it recursively. What is the best way to approach this type of problem? In a complex problem like this (well, complex to me!), how do I identify the base case and the recursive case?
Below is my iterative solution:
from typing import Generator
def binary_strings(string: str) -> Generator[str, None, None]:
listOfIndices = []
starterString = ''
for index, char in enumerate(string):
if char == 'X':
starterString = starterString + '0'
listOfIndices.append(index)
else:
starterString = starterString + char
def stringGenerator(): #generates the different combos
baseString = starterString
moddedString = ''
n = len(listOfIndices)
counter = 1
for i, character in enumerate(
starterString):
if i == 0:
yield starterString
else:
break
while counter <= n:
for i, chara in enumerate(baseString):
if i in listOfIndices:
moddedString = baseString[:i] + '1' + baseString[i + 1:]
yield moddedString
counter += 1
if counter > n and n >= 1:
counter = 1
n -= 1
baseString = moddedString
break
else:
continue
return stringGenerator()