有没有一种方法只能将递归的最后两个保存的值保留在字典中,而删除其余的?

时间:2019-08-09 13:00:34

标签: python-3.7

我正在使用备忘录将斐波那契数的最后计算值保存在字典中。由于(我想)我们不需要字典中先前计算的所有值,因此,我想删除它们。具体来说,我只想保留最后两个计算出的斐波那契数,有没有办法做到?

import sys
sys.setrecursionlimit(10000)
cache = {}


def fib(n):
    if n in cache:
        return cache[n]
    elif n <= 2:
        value = 1
    else:
        value = fib(n-1) + fib(n-2)
    cache[n] = value
    return value
print(fib(1000))

1 个答案:

答案 0 :(得分:0)

好,我找到了。

cache = {}
for x in range(1, 1000001):
    if x > 4:
        cache.pop(x-3, x-4)

    if x <= 2:
        value = 1
        cache[x] = value
    else:
        value = cache[x - 1] + cache[x - 2]
        cache[x] = value
print(value)