Last active
August 29, 2015 14:00
-
-
Save Hydrotoast/a1bb8db56458c78971e9 to your computer and use it in GitHub Desktop.
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
''' take from python.org example, using hot_swapping variables method ''' | |
def fib_hotswap(n): | |
a = 1 | |
b = 1 | |
for _ in range(1,n+1): | |
tmp = a + b | |
b = a | |
a = tmp | |
return b | |
''' take from class' note ICS 33 example, using recursive method ''' | |
def fib_recursive(n): | |
assert n>=0, 'fib cannot have negative n('+str(n)+')' | |
if n == 0: return 1 | |
elif n == 1: return 1 | |
else: return fib_recursive(n-1) + fib_recursive(n-2) | |
cache = {} | |
cache[0] = 1 | |
cache[1] = 1 | |
''' using cache ''' | |
def fib_recursive_cache(n): | |
assert n>=0, 'fib cannot have negative n('+str(n)+')' | |
if n == 0: return cache[0] | |
elif n == 1: return cache[1] | |
elif n in cache: return cache[n] | |
else: | |
cache[n] = fib_recursive_cache(n-1) + fib_recursive_cache(n-2) | |
return cache[n] |
Author
Hydrotoast
commented
May 3, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment