Created
January 21, 2018 05:29
-
-
Save maple3142/da888df53962f9e9e6307ad7900a9491 to your computer and use it in GitHub Desktop.
function cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
def cached(fn): | |
name=fn.__name__ | |
mycache={} | |
if not name in mycache: | |
mycache[name]={} | |
@wraps(fn) | |
def cachefn(*args,**kwargs): | |
key=(args,frozenset(kwargs)) | |
if key in mycache[name]: | |
return mycache[name][key] | |
else: | |
mycache[name][key]=fn(*args,**kwargs) | |
return mycache[name][key] | |
return cachefn | |
def counted(fn): | |
@wraps(fn) | |
def myfn(*args,**kwargs): | |
myfn.count+=1 | |
return fn(*args,**kwargs) | |
myfn.count=0 | |
return myfn | |
@counted | |
def fib(n): | |
if n==0 or n==1: | |
return 1 | |
return fib(n-1)+fib(n-2) | |
@counted | |
@cached | |
def cached_fib(n): | |
if n==0 or n==1: | |
return 1 | |
return cached_fib(n-1)+cached_fib(n-2) | |
print('fib(10)=',fib(10)) | |
print('fib.count=',fib.count) | |
print('cached_fib(10)=',cached_fib(10)) | |
print('cached_fib.count=',cached_fib.count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment