Last active
December 16, 2019 01:49
-
-
Save FerdinaKusumah/9d0d6bc277dc29eac53c8d985d6513f7 to your computer and use it in GitHub Desktop.
Memoization fibonacci
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
| import timeit | |
| from functools import wraps | |
| def memoize(func): | |
| cache = dict() | |
| @wraps(func) | |
| def to_cache(*args): | |
| if args in cache: | |
| return cache[args] | |
| result = func(*args) | |
| cache[args] = result | |
| return result | |
| return to_cache | |
| @memoize | |
| def fibonacci_memoize(n: int): | |
| if n == 0: | |
| return 0 | |
| elif n == 1: | |
| return 1 | |
| return fibonacci_memoize(n-1) + fibonacci_memoize(n-2) | |
| N = 35 | |
| print(timeit.timeit("fibonacci_memoize(N)", globals=globals(), number=1)) | |
| # 5.855500000073732e-05 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment