Created
January 30, 2017 00:37
-
-
Save willium/1989e11abe2c91aae65fec6b76d9ab62 to your computer and use it in GitHub Desktop.
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(fn): | |
cache = dict() | |
def closure(*args): | |
if args not in cache: | |
cache[args] = fn(*args) | |
return cache[args] | |
return closure |
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(f): | |
class memodict(dict): | |
def __getitem__(self, *key): | |
return dict.__getitem__(self, key) | |
def __missing__(self, key): | |
ret = self[key] = f(*key) | |
return ret | |
return memodict().__getitem__ | |
@memoize | |
def foo(a, b): | |
return a * b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment