我一直在尝试使用Python解决以下问题,但至今没有成功:
假设您有一个字符为“0”、“1”和“?”的字符串“?”符号可以是“0”或“1”。您的目标是打印给定字符串的所有可能输出。例如,字符串“0”的输出?1?“应为“0010”、“0011”、“0110”和“0111”
我试过以下方法:
def comb(S):
if not '?' in S:
yield S
else:
yield comb(S.replace('?','0',1))
yield comb(S.replace('?','1',1))
S = '0?1??011'
S_generator = comb(S)
for s in S_generator:
print s
The result is strange, and is not what I am trying to get:
<generator object comb at 0x106b2ceb0>
<generator object comb at 0x106b2cf00>
知道它为什么不工作了吗?我应该如何更改代码才能工作?
最佳答案
comb()
是一个生成器函数,当您这样做时-
yield comb(S.replace('?','0',1))
yield
语句不会自动循环生成器中的所有值并产生它们,您必须循环这些值并逐个产生它们,例如-def comb(S):
if not '?' in S:
yield S
else:
for i in comb(S.replace('?','0',1)):
yield i
for i in comb(S.replace('?','1',1)):
yield i
示例/演示-
>>> def comb(S):
... if not '?' in S:
... yield S
... else:
... for i in comb(S.replace('?','0',1)):
... yield i
... for i in comb(S.replace('?','1',1)):
... yield i
...
>>> for s in comb('abc?def?'):
... print(s)
...
abc0def0
abc0def1
abc1def0
abc1def1
>>> for s in comb('0?1?'):
... print(s)
...
0010
0011
0110
0111
>>> S = '0?1??011'
>>> for s in comb(S):
... print(s)
...
00100011
00101011
00110011
00111011
01100011
01101011
01110011
01111011
[编辑]:注意,从Python 3.3开始,您可以使用新的yield from语法:
yield from comb(S.replace('?','0',1))
yield from comb(S.replace('?','1',1))
关于python - 使用Python将一个字符替换为多个字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31714940/