给定起始字符串的Python bruteforce组合

给定起始字符串的Python bruteforce组合,python,python-3.x,brute-force,Python,Python 3.x,Brute Force,我正在尝试用Python和itertools做一个bruteforce字符串生成器。将_与_replacement结合起来似乎就可以了 gen = itertools.combinations_with_replacement('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',12) for combination in gen: check(''.join(combination)) 假设用户运行该程序数小时,最多可访问stri

我正在尝试用Python和itertools做一个bruteforce字符串生成器。将_与_replacement结合起来似乎就可以了

gen = itertools.combinations_with_replacement('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',12)
for combination in gen:
  check(''.join(combination))
假设用户运行该程序数小时,最多可访问string
aaaeabdouzIU

有没有办法给他们留下一个字符串,从那一点开始进行组合

因此,如果我传递字符串“
acc
”,它应该开始尝试“
acd
”、“
ace
”、


itertools.combinations\u with\u replacement
本机不提供此功能,有人可以实现此功能吗?

从源代码中获取原始代码,将combinations\u的代码复制为\u replacement code,但将第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)

如果你知道,给定一个组合,如何生成下一个,这很容易

一种方法是定义从组合到自然数的映射,以及从自然数到组合的逆映射。例如,您可以从中使用
base62\u编码
/
base62\u解码

以及生成给定起点的所有组合的生成器:

def generate_all(start='a'):
    while True:
        yield start
        start = next_comb(start)
for comb in generate_all(starting_point):
    print(comb)
用法:

for comb in generate_all():
    print(comb)
或者,要从起点恢复计算,请执行以下操作:

def generate_all(start='a'):
    while True:
        yield start
        start = next_comb(start)
for comb in generate_all(starting_point):
    print(comb)

我不知道有什么办法,但是itertools文档列出了一段等效的代码(实际上是两段),您可以尝试采用它来使用它。这也是一个额外的花絮。如果你不想把所有的字母都打出来<代码>导入字符串;string.ascii_字母您希望能够“递增”第一个输出以获得第二个,第n个输出以获得第n+1个。没有内置的方式。尝试将输出范围转换为整数范围并返回。如果这是可能的,您可以轻松地从序列中的任何位置开始递增整数,并生成您想要的任何子序列。最后一个else块应该是意外的-它属于for循环,而不是If循环。否则代码就不起作用了