2013-05-08 28 views
3

所有可能的數字比方說,我有這樣的字符串:生成帶面具

a = "123**7*9" 

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

12300709...12399799 

如何做到這一點與Python?

+0

作爲輸出的字符串還是整數? – 2013-05-08 09:41:56

回答

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("",repeat=c): 
...  print strs.format(*x)    #use `int()` to get an integer 

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

不錯的格式! – 2013-05-08 09:38:15

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) 

編輯,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

假設你有完全'3'星號 – jamylak 2013-05-08 09:50:25

+0

權,以及這是我想到了這樣的解決方案的問題... – 2013-05-08 09:58:38

+0

,但它不是那麼好當給出答案:) – user2257564 2013-05-08 10:02:56

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