从python中的给定模式(通配符)生成所有二进制字符串

时间:2017-08-16 05:03:49

标签: python

给定一个模式,我们需要通过0 and 1填充模式中缺少的位置来生成所有可能的二进制数。

E.g。

Pattern = "x1x";

输出:

010 
110 
011 
111

6 个答案:

答案 0 :(得分:5)

这是相对简单的递归,不需要使用库:

def process(patt):
    if "x" not in patt:
        print(patt)
    else:
        process(patt.replace("x", "0", 1))
        process(patt.replace("x", "1", 1))


process("x1x")

<强>输出

010
011
110
111

答案 1 :(得分:0)

尝试这种方式:

def pattern(str1, idx):
    str = list(str1)
    if idx == len(str):
        print(''.join(str))
        return 0
    if str[idx] == 'x':
        # replace 'x' by '0' and recurse
        str[idx] = '0'
        pattern(str, idx + 1)
        # replace 'x' by '1' and recurse
        str[idx] = '1'
        pattern(str, idx + 1)
        # No need to backtrack as string is passed by value to the function

    else:
        pattern(str, idx + 1)

str = "x1x"
pattern(str, 0)

输出:

010
011
110
111

答案 2 :(得分:0)

我认为您可以使用itertools.product([0, 1], repeat=2),然后过滤输出以满足您的需求:

>>> import itertools
>>>
>>> [''.join(x) for x in itertools.product(['0', '1'], repeat=3) if x[1] == '1']
['010', '011', '110', '111']

答案 3 :(得分:0)

这是使用itertools解决问题的一种可能方法:

import itertools

pattern = "x1x"

a = [['0','1'] if (c == 'x') else c for c in pattern]
b = [''.join(lst) for lst in list(itertools.product(*a))]
for s in b:
    print(s)

输出:

010 
110 
011 
111

答案 4 :(得分:0)

这是另一个使用python正则表达式模块 re itertool ,如其他答案所示。

import re
import itertools

pattern = 'x1x'
patt = re.compile(pattern.replace('x', '.'))

pattern_length = len(pattern)

perms = [ '1','0'] *pattern_length

ls = list()
for x in itertools.permutations(perms, pattern_length):
  ls.append(x)

func = lambda x: ''.join(x)

keep = list()
for x in ls:
  x_ = func(x)
  if patt.match(x_) and not x_ in keep:
    keep.append(x_)

for k in keep:
  print k

输出中:

110
111
011
010

答案 5 :(得分:0)

这是使用列表(队列)的另一种方法。它弹出列表中的第一个条目,并在输入字符串中找到第一个出现的“ x”,然后将其替换为“ 0”,然后替换为“ 1”,然后将这两个新字符串附加到列表中。直到列表中没有“ x”为止。我相信这是使用简单的while循环的最简单方法之一:

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)

驱动程序代码:

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

输出:

['11010', '11011', '11110', '11111']
相关问题