Created
November 30, 2016 16:07
-
-
Save jovianlin/e6d34085f87be6efd2a95d1b8f86da4c to your computer and use it in GitHub Desktop.
fibonacci with LRU cache for memoization
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
from functools import lru_cache | |
@lru_cache(maxsize=100) | |
def fibonacci(n): | |
# Check that the input is a positive integer | |
if type(n) != int: | |
raise TypeError("n must be a positive int") | |
if n < 1: | |
raise ValueError("n must be a positive int") | |
# Compute the Nth term | |
return 1 if (1<=n<=2) else (fibonacci(n-1) + fibonacci(n-2)) | |
if __name__ == "__main__": | |
for n in range(1, 101): | |
print("{0:<5} : {1}".format(n, fibonacci(n))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment