Advertisement
haiv

How to cache a function

Apr 23rd, 2013
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.43 KB | None | 0 0
  1. def cache(func):
  2.     'Optimize a pure function by caching prior results'
  3.     prior_results = {}
  4.     @wraps(func)
  5.     def newfunc(*args):
  6.         if args in prior_results:
  7.             return prior_results[args]
  8.         result = func(*args)
  9.         prior_results[args] = result
  10.         return result
  11.     return newfunc
  12.  
  13. @cache
  14. def fibo(n):
  15.     if n == 0: return 0
  16.     if n == 1: return 1
  17.     return fibo(n-1) + fibo(n-2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement