Skip to content

Instantly share code, notes, and snippets.

@jovianlin
Created November 30, 2016 16:07
Show Gist options
  • Save jovianlin/e6d34085f87be6efd2a95d1b8f86da4c to your computer and use it in GitHub Desktop.
Save jovianlin/e6d34085f87be6efd2a95d1b8f86da4c to your computer and use it in GitHub Desktop.
fibonacci with LRU cache for memoization
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