【问题标题】:Generate all possible numbers with mask使用掩码生成所有可能的数字
【发布时间】:2016-12-02 18:19:57
【问题描述】:

假设我有一个类似的字符串:

a = "123**7*9"

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

12300709...12399799

如何用 Python 做到这一点?

【问题讨论】:

  • 字符串或整数作为输出?

标签: python combinations mask


【解决方案1】:

您可以使用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
....

【讨论】:

    【解决方案2】:

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

    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)
    

    编辑,繁荣:

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

    【讨论】:

    • 假设你正好有3星号
    • 我想过这样的解决方案,但它不像给定的答案那么好:)
    • 同样的事情,但现在可以使用任意数量的通配符。
    【解决方案3】:

    递归变体:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多