Skip to content

Instantly share code, notes, and snippets.

@dsaw
Created August 20, 2018 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsaw/c2c7f5fa3695af65b5adb706381befd7 to your computer and use it in GitHub Desktop.
Save dsaw/c2c7f5fa3695af65b5adb706381befd7 to your computer and use it in GitHub Desktop.
Memoized fibonacci in Python
# https://dbader.org/blog/python-memoization
# Example learned from there
def memoize(func):
cache = dict()
def memoized_func(*args):
if args in cache:
return cache[args]
result = func(*args)
cache[args] = result
return result
return memoized_func
def fibonacci(N):
if N == 0:
return 0
elif N == 1:
return 1
return fibonacci(N-1) + fibonacci(N-2)
import timeit
print("Standard Fibonacci -")
print(timeit.timeit('fibonacci(35)',globals=globals(), number=1))
print("Memoized Fibonacci -")
memoized_fib = memoize(fibonacci)
# not much speed gain first time.
print(timeit.timeit('memoized_fib(35)',globals=globals(), number=1))
print("Again - Memoized Fibonacci -")
# huge speedup with cache use
print(memoized_fib.__closure__[0].cell_contents)
print(timeit.timeit('memoized_fib(35)',globals=globals(), number=1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment