Skip to content

Instantly share code, notes, and snippets.

@amitsaha
Created June 27, 2012 09:13
Show Gist options
  • Select an option

  • Save amitsaha/3002711 to your computer and use it in GitHub Desktop.

Select an option

Save amitsaha/3002711 to your computer and use it in GitHub Desktop.
Simple Memoization demo using Python decorators
''' Simple Memoization demonstration using decorators'''
#dictionary
global cached
cached = {}
def cache(n):
def wrap(f):
def wrapped_f(*args):
global cached
cached['{0:s}'.format(str(args[0]))] = f(args[0])
return wrapped_f
return wrap
@cache(1)
def fact(n):
prod = 1
for i in xrange(1,n+1):
prod = prod*i
return prod
#entry point
if __name__ == '__main__':
while True:
n = input('Enter a number:: ')
try:
print 'Hit:: Factorial is:: {0:d}'.format(cached[str(n)])
except KeyError:
fact(n)
print 'Miss:: Factorial is:: {0:d}'.format(cached[str(n)])
Sample Output:
Enter a number:: 5
Miss:: Factorial is:: 120
Enter a number:: 10
Miss:: Factorial is:: 3628800
Enter a number:: 5
Hit:: Factorial is:: 120
Enter a number:: 5
Hit:: Factorial is:: 120
Enter a number:: 6
Miss:: Factorial is:: 720
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment