Last active
December 18, 2015 16:58
-
-
Save pakmans/5815071 to your computer and use it in GitHub Desktop.
Naive implementation to get the nth element of the Fibonacci sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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