Created
August 6, 2016 13:23
-
-
Save myarik/e64748a7986dbd77e476481f3e474bdf 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
# 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