Advertisement
1nikitas

Untitled

Mar 16th, 2022
1,046
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.40 KB | None | 0 0
  1. def cached(func):
  2.     cache = {}
  3.  
  4.     def a(*args, **kwargs):
  5.         nonlocal cache
  6.         if not cache.get(args):
  7.             g = func(*args, **kwargs)
  8.             cache[args] = g
  9.             return g
  10.         else:
  11.             return cache[args]
  12.  
  13.     return a
  14.  
  15.  
  16. @cached
  17. def fib(n):
  18.     if n == 1 or n == 2:
  19.         return 1
  20.     else:
  21.         return fib(n - 1) + fib(n - 2)
  22.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement