ArtofShadows.com see more from the shoots! NSFW

# Python – Fibonacci sequence ft. Recursion and Memoization for speed.

This code comes from YouTube channel Socratica, great video on Recursive function to print out the Fibonacci sequence. The code starts with a simple Recursive function to print the first 10 numbers, it works great until you add more numbers and then your computer will slow to a crawl. So Memoization was added aka caching then function had some error checking to prevent floats, negative integers, and bad inputs of like ‘one’.

``````# Fibonacci Sequence first 8, goes on forever.
# 1, 1, 2, 3, 5, 8, 13, 21
# 1 + 1
# 1 + 2
# 2 + 3
# 3 + 5 etc.``````
``````# First simple version, slow when adding more of the sequence and accepts wrong data types.

def fibonacci(n) :
if n == 1:
return 1
elif n == 2:
return 1
elif n > 2:
return fibonacci(n - 1) + fibonacci(n - 2)
for n in range(1, 11):
# Change the 11 above to 101 and watch this code slow to a crawl, the fix will be on next code snippet below.
print(n, ':', fibonacci(n))``````
``````# Second version with more error checking and lru_cache support, very fast

# Memoization aka caching, without this the code will be slow

from functools import lru_cache
@lru_cache(maxsize = 1000)

def fibonacci(n) :
if type(n) != int:
raise TypeError('n must be a positive int')
if n < 1:
raise ValueError('n must be a positive int')
if n == 1:
return 1
elif n == 2:
return 1
elif n > 2:
return fibonacci(n - 1) + fibonacci(n - 2)
for n in range(1, 101):
print(n, ':', fibonacci(n))``````