Skip to content

Instantly share code, notes, and snippets.

@hillscottc
Created May 30, 2014 15:56
Show Gist options
  • Save hillscottc/c68a2b85ec2f1bc145d2 to your computer and use it in GitHub Desktop.
Save hillscottc/c68a2b85ec2f1bc145d2 to your computer and use it in GitHub Desktop.
Decorator for memoization via 'cache' dictionary.
def memoize(func):
"""Decorator for memoization via 'cache' dictionary."""
cache = {}
def memoed_func(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
memoed_func.cache = cache
return memoed_func
@memoize
def fib(n):
"""Demos use of memoization decorator. """
if n <= 2:
return 1
else:
return fib(n-1) + fib(n-2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment