Advertisement
themoosemind

Fibonacci example with decorators

Nov 10th, 2013
363
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.49 KB | None | 0 0
  1. #!/usr/bin/bash python
  2. from functools import wraps
  3.  
  4. def memoize(obj):
  5.     """Function wrapper for memorizing stuff."""
  6.     cache = {}
  7.  
  8.     @wraps(obj)
  9.     def memoizer(*args, **kwargs):
  10.         """Actual memorizer."""
  11.         if args not in cache:
  12.             cache[args] = obj(*args, **kwargs)
  13.         return cache[args]
  14.     return memoizer
  15.  
  16. @memoize
  17. def fib(n):
  18.     """Return the fibonacci sequence."""
  19.     if n < 2:
  20.         return n
  21.     else:
  22.         return fib(n-1) + fib(n-2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement