Created
March 4, 2021 17:00
-
-
Save pingswept/5eb99faeebcdc1e459b8d75cb97ad4d1 to your computer and use it in GitHub Desktop.
Demo of how to memoize a function 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
import functools | |
import timeit | |
import time | |
@functools.lru_cache(maxsize=None) | |
def fib(n): | |
if n < 2: | |
return n | |
return fib(n-1) + fib(n-2) | |
#print(timeit.timeit('time.sleep(0.05)', number=100)) | |
print(timeit.timeit('fib(10)', globals=globals())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment