Created
August 20, 2018 17:11
-
-
Save dsaw/c2c7f5fa3695af65b5adb706381befd7 to your computer and use it in GitHub Desktop.
Memoized fibonacci in Python
This file contains 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
# 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