怎么样:
from itertools import productdef filler(word, from_char, to_char): options = [(c,) if c != from_char else (from_char, to_char) for c in word] return (''.join(o) for o in product(*options))
这使
>>> filler("1xxx1", "x", "5")<generator object <genexpr> at 0x8fa798c>>>> list(filler("1xxx1", "x", "5"))['1xxx1', '1xx51', '1x5x1', '1x551', '15xx1', '15x51', '155x1', '15551']
(请注意,您似乎丢失了
15x51。)基本上,首先,我们为源单词中的每个字母列出每个可能的目标:
>>> word = '1xxx1'>>> from_char = 'x'>>> to_char = '5'>>> [(c,) if c != from_char else (from_char, to_char) for c in word][('1',), ('x', '5'), ('x', '5'), ('x', '5'), ('1',)]
然后,我们使用
itertools.product这些可能性的笛卡尔积,并将结果结合在一起。
对于奖励积分,进行修改以接受替换字典。:^)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)