Created
May 23, 2012 11:08
-
-
Save apalala/2774589 to your computer and use it in GitHub Desktop.
Memoization in Python
This file contains 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
#!/usr/bin/env python | |
# -*- encoding:utf-8 -*- | |
""" | |
Solution to Project Euler Problem | |
http://projecteuler.net/ | |
by Apalala <[email protected]> | |
(cc) Attribution-ShareAlike | |
http://creativecommons.org/licenses/by-sa/3.0/ | |
Memoization. | |
""" | |
import functools | |
def memoize(func): | |
func.cache = {} | |
def memoize(*args, **kw): | |
if kw: # frozenset is used to ensure hashability | |
key = args, frozenset(kw.iteritems()) | |
else: | |
key = args | |
cache = func.cache | |
if key in cache: | |
return cache[key] | |
else: | |
cache[key] = result = func(*args, **kw) | |
return result | |
return functools.update_wrapper(memoize, func) | |
if __name__ == '__main__': | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment