Skip to content

Instantly share code, notes, and snippets.

@maple3142
Created January 21, 2018 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maple3142/da888df53962f9e9e6307ad7900a9491 to your computer and use it in GitHub Desktop.
Save maple3142/da888df53962f9e9e6307ad7900a9491 to your computer and use it in GitHub Desktop.
function cache
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