Python中的内存错误 - 如何使用更少的内存?

时间:2018-02-18 01:23:14

标签: python python-3.x

import string
from itertools import product

l = string.ascii_letters+string.digits+'-'+'_'    
def combinations(a,times):
    comb = list(product(a, repeat=times))
    i = 0
    a = []
    while(i < len(comb)):
        s = ''.join(comb[i])
        a.append(s)
        i+=1
    return a
a = combinations(l,4)
print(a)

我有一个随机的哈希字符串,最多可以包含10个字符,我想检查每个字符串的可能性,哈希并比较哈希值,直到我得到字符串。但是,当我想拥有4个字符串的所有可能性时,它会给我一个内存错误。我想最多10个字符。

这是我得到的错误:

Traceback (most recent call last):
File "source_file.py", line 14, in <module>
    a = combinations(l,4)
File "source_file.py", line 6, in combinations
    comb = list(product(a, repeat=times))
MemoryError

1 个答案:

答案 0 :(得分:1)

喜欢这个......

要节省内存,您需要使用生成器,因此整个列表不会存储在内存中。

def combinations(a,times):
    for combination in product(a, repeat=times):
        yield ''.join(combination)

然后你可以像这样使用它。

l = string.ascii_letters+string.digits+'-'+'_' 
combination_generator = combinations(l, 4)

# This will work, but takes a few minutes
for c in combination_generator:
    print(c)

可是...

你不再失去记忆,现在你已经没时间了。十个字符串有64 ^ 10种组合。那是1,152,921,504,606,846,976。在你的生活中,你很可能永远无法达到那个发电机的终点。