Skip to content

Instantly share code, notes, and snippets.

@husobee
Last active April 27, 2017 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save husobee/64c592726cde2609a02c35343fed11ae to your computer and use it in GitHub Desktop.
Save husobee/64c592726cde2609a02c35343fed11ae to your computer and use it in GitHub Desktop.
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]
@lru_cache(None)
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