from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n <= 1:
return 1
return fib(n - 2) + fib(n - 1)
def fib(n):
cache = {}
def impl(ni):
nonlocal cache
if ni <= 1:
return 1
if ni not in cache:
cache[ni] = impl(ni - 2) + impl(ni - 1)
return cache[ni]
return impl(n)
Un peu modifié sur la base du commentaire de @shiracamus ↓
def fib(n, cache={0:1, 1:1}):
if n not in cache:
cache[n] = fib(n - 2) + fib(n - 1)
return cache[n]
def fib(n):
if n <= 1:
return 1
return fib(n - 2) + fib(n - 1)
Recommended Posts