Hide cache
state.
Follow EAFP.
def _make_fibonacci(): cache = {} def fib(b): if 0 <= b <= 1: return b elif b < 0: return None try: res = cache[b] except KeyError: res = fib(b-1) + fib(b-2) cache[b] = res return res return fib fibonacci = _make_fibonacci()
def fibonacci(b, cache={}):if b <= 1:return bif b in cache:return cache[b]cache[b] = fibonacci(b-1, cache) + fibonacci(b-2, cache)return cache[b]- def _make_fibonacci():
- cache = {}
- def fib(b):
- if 0 <= b <= 1:
- return b
- elif b < 0:
- return None
- try:
- res = cache[b]
- except KeyError:
- res = fib(b-1) + fib(b-2)
- cache[b] = res
- return res
- return fib
- fibonacci = _make_fibonacci()