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

标签 python python-3.x brute-force

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

相关文章:

python - 使用 Try 和 Except 时如何在 Python 中单元测试错误

python-3.x - Flask sqlalchemy 和 marshmallow 的多对多关系

asp.net - ASP.net EventValidation 和 ViewState 是否可以减轻暴力攻击?

python - 如何确定一个整数在列表的列表列表中有多少个唯一的其他项目?

相当于 uber-jar 的 Python

python - 如何分析conda的依赖树

algorithm - 生成具有给定体积的所有立方体

java - 暴力破解: count number of sub strings in a string array

python - print(len(list_a)) 打印为两个,但 print(list_a) 打印为 []

python - 如何在Python2 CLI中制作交互式选择菜单?