我正在尝试用 Python 做一个强力字符串生成器,itertools.combinations_with_replacement
似乎可以解决问题。
gen = itertools.combinations_with_replacement('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',12)
for combination in gen:
check(''.join(combination))
假设用户运行程序几个小时并达到字符串 aaaeabdouzIU
。
有没有什么办法给定一个字符串,让他们从那一点开始进行组合?
所以如果我传递字符串 'acc
' 它应该开始尝试 'acd
','ace
',.. .
itertools.combinations_with_replacement
本身不提供此功能,是否有人可以通过任何方式实现此功能?
最佳答案
从 itertools man page 中获取原始代码复制 combinations_with_replacement 代码,但将第 7 行替换为从您输入的单词开始的新索引。
inputStr='acc'
indices=[pool.index(l) for l in inputStr]
然后运行手册页中的其余代码。
编辑:对于一个完整的运行函数:
def combinations_with_replacement(iterable, r, startWord=None):
# combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
pool = tuple(iterable)
n = len(pool)
if not n and r:
return
if startWord is None:
indices = [0] * r
else:
assert len(startWord) == r
indices = [pool.index(l) for l in startWord]
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != n - 1:
break
else:
return
indices[i:] = [indices[i] + 1] * (r - i)
yield tuple(pool[i] for i in indices)
关于给定起始字符串的 Python 暴力组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30904126/