Skip to content

Instantly share code, notes, and snippets.



Last active Apr 27, 2017
What would you like to do?
examples of fibonacci in python
from functools import reduce, lru_cache
fib_bad = lambda n:reduce(lambda x,n:[x[1],x[0]+x[1]], range(n),[0,1])[0]
def fib_naive(n):
""" fib_naive - naive solution to the fibonacci """
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
def fib_recursive(n):
""" fib_recursive - recursive solution to the fibonacci """
if n==1 or n==2:
return 1
return fib_recursive(n-1)+fib_recursive(n-2)
def fib_memoize(fn, arg):
""" fib_memoize - memoized solution to fibonacci """
memo = {}
if arg not in memo:
memo[arg] = fib_naive(arg)
return memo[arg]
def fib_memoize2(n):
""" fib_memoize2 - another memoized solution to fibonacci """
if n < 2:
return n
return fib_memoize2(n-1) + fib_memoize2(n-2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment