Python 给定起始字符串的暴力组合

Python bruteforce combinations given a starting string

我正在尝试在 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]

然后 运行 手册页中的其余代码。

编辑:对于完整的 运行ning 函数:

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)

如果您知道给定一个组合如何生成下一个组合,就很容易了。

一种方法是定义从组合到自然数的映射,以及从自然数到组合的逆映射。例如,您可以使用 base62_encode/base62_decode 来自 Base 62 conversion

def next_comb(s):
    return base62_encode(1+base62_decode(s))

和一个生成器来生成给定起点的所有组合:

def generate_all(start='a'):
    while True:
        yield start
        start = next_comb(start)

用法:

for comb in generate_all():
    print(comb)

或者,从起点继续计算:

for comb in generate_all(starting_point):
    print(comb)