生成密码列表时发生内存错误

时间:2019-07-18 16:22:34

标签: python algorithm out-of-memory itertools cartesian-product

我正在尝试生成长度在1-5个字符之间的所有可能的密码,其中可能的字符是小写字母,大写字母和10位数字。

为了简单起见,我将可能的字符限制为小写字母和十位数字,密码的长度限制为3-5个字符。

import itertools
charMix = list("abcdefghijklmnopqrstuvwxyz1234567890")
mix = []
for length in range(3, 6):
   temp = [''.join(p) for p in itertools.product(charMix, repeat=length)]
   mix.append(temp)

但是,我在temp分配行遇到内存错误,不知道如何克服它们:(

有没有一种方法可以生成这些没有内存错误的密码?

1 个答案:

答案 0 :(得分:1)

由于您实际上提到了术语生成,因此如果可以满足您的用例,请在此处考虑一个generator

from typing import Generator
import itertools

def make_pws(join="".join) -> Generator[str, None, None]:
    charMix = "abcdefghijklmnopqrstuvwxyz1234567890"
    for length in range(3, 6):
       for p in itertools.product(charMix, repeat=length):
           yield join(p)

您可以像序列一样遍历此结果,而无需将所有内容都放在内存中

>>> pws = make_pws()
>>> next(pws)
'aaa'
>>> next(pws)
'aab'
>>> next(pws)
'aac'
>>> next(pws)
'aad'
>>> for pw in make_pws():
...     # process each one at a time
相关问题