所有可能的8个符号字符串生成器。暴力破解8个符号密码。python

-1 投票
4 回答
13939 浏览
提问于 2025-04-16 19:11

我需要写一个生成器,能够产生所有可能的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']

4 个回答

2
import itertools
itertools.combinations_with_replacement(leters, 8)

顺便说一下,"letters"这个词里有两个"T"。

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

编辑:让它返回字符串而不是元组:

7

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的解决方案那样。

撰写回答