Skip to content

Instantly share code, notes, and snippets.

@apalala
Created May 23, 2012 11:08
Show Gist options
  • Save apalala/2774589 to your computer and use it in GitHub Desktop.
Save apalala/2774589 to your computer and use it in GitHub Desktop.
Memoization in Python
#!/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