所有可能的8个符号字符串的生成器.Brute force 8符号密码.蟒蛇



我需要编写生成所有可能的8个符号字符串的生成器。来自这样的符号阵列:

leters = ['1','2','3','4','5','6','7','8','9','0','q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m']

骨架看起来像这样:

def generator():
    """
    here algorithm
    """
    yield string

假设返回这样的列表['00000001','00000002','00000003', ......'mmmmmmmm']

itertools.combinations()itertools.combinations_with_replacement()返回生成器

>>> letters = ['a', 'b', 'c']
>>> from itertools import combinations

我在示例中使用print()来说明输出。将其替换为yield,以获得生成器。

>>> for c in combinations(letters, 2): 
        print(c)
... 
('a', 'b')
('a', 'c')
('b', 'c')
>>> for c in combinations(letters, 2): 
        print(''.join(c))
... 
ab
ac
bc
>>> 
>>> for c in itertools.combinations_with_replacement(letters, 2): 
        print(''.join(c))
... 
aa
ab
ac
bb
bc
cc

如果你对所有包含英文字母和数字的8个字母的密码强行使用它,你会看到迭代超过2.8万亿个字符串的

编辑如果您不知何故知道没有重复元素,请使用permutations

>>> for c in itertools.permutations(letters, 2): 
        print(''.join(c))
... 
ab
ac
ba
bc
ca
cb

这为您提供abba

对于最通用的蛮力序列,使用itertools.product()作为Cosmologicon的解决方案

itertools.product(leters, repeat=8)

编辑:让它给你字符串而不是元组:

def generator(leters):
    a = itertools.product(leters,repeat=3)
    while a:
        yield "".join(a.next())
import itertools
itertools.combinations_with_replacement(leters, 8)

顺便说一下,字母有两个T。

我也想知道如何做到这一点,这就是我想到的。我尝试了几种方法,但当我这样写的时候,它比其他方法快得多。。。如果我没有看到,请稍等

import string
from itertools import permutations
[print(*p,sep='')for p in permutations(list(string.ascii_letters+string.punctuation+string.digits),8)]

最新更新