Skip to content

Instantly share code, notes, and snippets.

@Hydrotoast
Last active August 29, 2015 14:00
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 Hydrotoast/a1bb8db56458c78971e9 to your computer and use it in GitHub Desktop.
Save Hydrotoast/a1bb8db56458c78971e9 to your computer and use it in GitHub Desktop.
''' 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]
@Hydrotoast
Copy link
Author

First calculation 35th number of Fibonacci -> 14930352

Mesuare time take for "hot swapping" method -> 5.6564998885733075e-05 seconds

Second calculation 35th number of Fibonacci -> 14930352

Mesuare time take for "recursive" method -> 4.214802125999995 seconds

Second calculation 35th number of Fibonacci -> 14930352

Mesuare time take for "recursive cache" method -> 4.5699000111198984e-05 seconds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment