Python Memory Error while iterating to a big range

后端 未结 3 2028
栀梦
栀梦 2021-01-14 23:44
total = 0
x = 2**32
for i in range(x):
    total = total + i;
print(total) 

I am getting a MemoryError<

3条回答
  •  执笔经年
    2021-01-15 00:00

    For a brute-force approach, try this:

    x = sum(i for i in xrange(2**32))
    

    The above will be more efficient, as it uses xrange to generate the numbers lazily, and it also uses a generator expression with sum() to avoid generating temporary data that gets discarded immediately.

    But that will still take some time, as 2**32 is a big number. The smart way to solve this problem is to use a formula, as suggested by @DeepSpace:

    n = 2**32 - 1
    x = (n * (n + 1)) / 2
    

提交回复
热议问题