Generate all binary strings from given pattern(wildcard) in python

Viewed 1652

Given a pattern , we need to generate all possible binary numbers by filling the missing places in the pattern by 0 and 1.

E.g.

Pattern = "x1x";

Output :

010 
110 
011 
111
6 Answers

Here is another method using list(queue). It pops the first entry in the list and finds the first occurrence of "x" in the input string and replaces it by "0" and then "1" and then append these 2 new strings to the list. It goes until there is no "x" left in the list. I believe this one is one of the simplest way with a simple while loop:

def pattern_processor(list):
    while "x" in list[0]:
        item=list.pop(0)
        list.append(item.replace("x", "0", 1))
        list.append(item.replace("x", "1", 1))
    return(list)

Driver code:

if __name__ == "__main__":
    print(pattern_processor(["11x1x"]))

output:

['11010', '11011', '11110', '11111']
Related