Skip to content

Instantly share code, notes, and snippets.

@pakmans
Last active December 18, 2015 16:58
Show Gist options
  • Save pakmans/5815071 to your computer and use it in GitHub Desktop.
Save pakmans/5815071 to your computer and use it in GitHub Desktop.
Naive implementation to get the nth element of the Fibonacci sequence
""" Naive implementation to get the nth element of the Fibonacci sequence """
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def memoize(f):
cache = {}
def aux(*args, **kargs):
k = (args, tuple(kargs.items()))
if k not in cache:
cache[k] = f(*args, **kargs)
return cache[k]
return aux
@memoize
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment