Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Last active October 8, 2015 21:40
Show Gist options
  • Save goldsborough/fb0cd4c4272ffa9db4fc to your computer and use it in GitHub Desktop.
Save goldsborough/fb0cd4c4272ffa9db4fc to your computer and use it in GitHub Desktop.
A python function to memoize DP problems with multiple-index keys
def memoize(*indices):
def decorator(function):
cache = {}
def proxy(*args, **kwargs):
key_args = [args[i] for i in indices] if indices else args
key = tuple(key_args)
if key not in cache:
cache[key] = function(*args, **kwargs)
return cache[key]
return proxy
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment