Created
June 27, 2012 09:13
-
-
Save amitsaha/3002711 to your computer and use it in GitHub Desktop.
Simple Memoization demo using Python decorators
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
| ''' 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