Ad

Hide cache state.

Follow EAFP.

Code
Diff
  • 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 b
    • if 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()
Code
Diff
  • def fibonacci(b):
        if 0 <= b <= 1:
            return b
        elif b < 0:
            return None
        return fibonacci(b-1) + fibonacci(b-2)
    • def fibonacci(b):
    • if b in [0, 1]: return b
    • return fibonacci(b-1) + fibonacci(b-2)
    • if 0 <= b <= 1:
    • return b
    • elif b < 0:
    • return None
    • return fibonacci(b-1) + fibonacci(b-2)