使用掩码生成所有可能的数字

时间:2013-05-08 09:30:41

标签: python combinations mask

假设我有一个字符串:

a = "123**7*9"

我需要生成所有可能的组合:

12300709...12399799

如何用Python做到这一点?

3 个答案:

答案 0 :(得分:11)

您可以使用itertools.product和字符串格式:

>>> from itertools import product
>>> strs = "123**7*9"
>>> c = strs.count("*")              #count the number of "*"'s
>>> strs = strs.replace("*","{}")    #replace '*'s with '{}' for formatting
>>> for x in product("0123456789",repeat=c):
...     print strs.format(*x)               #use `int()` to get an integer

12300709
12300719
12300729
12300739
12300749
12300759
12300769
12300779
12300789
12300799
....

答案 1 :(得分:1)

你也可以这样做,只使用标准库:

a = "123**7*9"
a = a.replace("*", "%d")
for x in range(10):
    for y in range(10):
        for z in range(10):
            print a % (x,y,z)

EDIT,BOOM:

a = "123**7*9"
c = a.count("*")
a = a.replace("*", "%s")
for x in range(10**c):
    print a % tuple(list("%03d" % x))

答案 2 :(得分:0)

递归变体:

def combinate(pattern, order=0):
    if pattern:
        for val in combinate(pattern[:-1], order+1):
            last_value = pattern[-1]
            if last_value == '*':
                for gen in xrange(10):
                    value = gen * (10**order) + val
                    yield value
            else:
                value = int(last_value)*(10**order)+val
                yield value
    else:
        yield 0


for i in combinate('1*1**2'):
    print i