Last active
October 8, 2015 21:40
-
-
Save goldsborough/fb0cd4c4272ffa9db4fc to your computer and use it in GitHub Desktop.
A python function to memoize DP problems with multiple-index keys
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
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