简体   繁体   English

Python 中超出内存限制

[英]Memory limit exceeded in Python

I am solving a problem that needs either a list of integers or a dictionary of size 10^18.我正在解决一个需要整数列表或大小为 10^18 的字典的问题。 Upon running the code the compiler throws an error message saying "Memory Limit Exceeded".运行代码时,编译器会抛出一条错误消息,指出“超出内存限制”。

Here is my code:这是我的代码:

def fun(l, r, p):
    #f = [None, 1, 1]
    f = {0:0, 1:1, 2:1}
    su = 0
    for i in range(1, r):
        if i%2 == 0:
            f[i+2] = 2*f[i+1] - f[i] + 2
            #f.append(2*f[i+1] - f[i] + 2)
        else:
            f[i+2] = 3*f[i]
            #f.append(3*f[i])

    for k in range(l, r):
        su = su + f[k]

    su = (su + f[r]) % p
    print(su)

t, p = input().split()
p = int(p)
t = int(t)
#t = 3
#p = 100000007
for i in range(t):
    l , r = input().split()
    l = int(l)
    r = int(r)
    fun(l, r, p)

It is showing memory limit exceeded with a maximum memory usage of 306612 KiB.它显示超出内存限制,最大内存使用量为 306612 KiB。

Two observations here:这里有两个观察:

  • You don't need to store all numbers simultaneously.您不需要同时存储所有数字。 You can use the deque and generator functions to generate the numbers by keeping track of only the last three digits generated instead of the entire sequence.您可以使用 deque 和 generator 函数通过仅跟踪生成的最后三位数字而不是整个序列来生成数字。

     import itertools from collections import deque def infinite_fun_generator(): seed = [0, 1, 1] dq = deque(maxlen=2) dq.extend(seed) yield from seed for i in itertools.count(1): if i % 2 == 0: dq.append(2 * dq[-1] - dq[-2] + 2) else: dq.append(3 * dq[-2]) yield dq[-1] def fun(l, r, p): funs = itertools.islice(infinite_fun_generator(), l, r + 1) summed_funs = itertools.accumulate(funs, lambda a, b: (a + b) % p) return deque(summed_funs, maxlen=1)[-1]
  • You might have a better chance asking this in Math.SE since I don't want to do the math right now, but just like with the Fibonacci sequence there's likely an analytic solution that you can use to compute the nth member of the sequence analytically without having to iteratively compute the intermediate numbers and it may even be possible to analytically derive a formula to compute the sums in constant time.你可能有更好的机会在 Math.SE 中问这个问题,因为我现在不想做数学运算,但就像斐波那契数列一样,可能有一个解析解,您可以用它来分析地计算序列的第 n 个成员无需迭代计算中间数,甚至可以通过分析推导出一个公式来计算恒定时间内的总和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM