Last active
August 29, 2015 14:08
-
-
Save hildensia/91eb71f29f95c2f39396 to your computer and use it in GitHub Desktop.
Dynamic Programming as Decorator
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 decorator import decorator | |
| def _dynamic_programming(f, *args, **kwargs): | |
| try: | |
| f.cache[args] | |
| except KeyError: | |
| f.cache[args] = f(*args, **kwargs) | |
| return f.cache[args] | |
| def dynamic_programming(f): | |
| f.cache = {} | |
| return decorator(_dynamic_programming, f) | |
| @dynamic_programming | |
| def fib(n): | |
| if n <= 1: | |
| return 1 | |
| else: | |
| return fib(n-1) + fib(n-2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment