所有可能的8个符号串的生成器。暴力8符号密码。Python

2024-10-05 14:30:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写生成所有可能的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']


Tags: 字符串列表stringheredef符号数组generator
3条回答

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()

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

相关问题 更多 >