Skip to content

Instantly share code, notes, and snippets.

@myarik
Created August 6, 2016 13:23
Show Gist options
  • Save myarik/e64748a7986dbd77e476481f3e474bdf to your computer and use it in GitHub Desktop.
Save myarik/e64748a7986dbd77e476481f3e474bdf to your computer and use it in GitHub Desktop.
# http://codereview.stackexchange.com/questions/137898/memoization-with-factorial-in-python
import functools
def memoize(func):
cache = func.cache = {}
@functools.wraps(func)
def wrapper(n):
if n not in cache:
cache[n] = func(n)
return cache[n]
return wrapper
def memodict(f):
""" Memoization decorator for a function taking a single argument """
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
@memodict
# @memoize
def factorial(n):
"""calculates n! with a simple recursive algorithm"""
if n == 0:
return 1
else:
return n * factorial(n-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment