Skip to content

Instantly share code, notes, and snippets.

@hildensia
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save hildensia/91eb71f29f95c2f39396 to your computer and use it in GitHub Desktop.

Select an option

Save hildensia/91eb71f29f95c2f39396 to your computer and use it in GitHub Desktop.
Dynamic Programming as Decorator
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