Skip to content

Instantly share code, notes, and snippets.

@ecounysis
Last active August 29, 2015 14:01
Show Gist options
  • Save ecounysis/5b81b09869dc654edb18 to your computer and use it in GitHub Desktop.
Save ecounysis/5b81b09869dc654edb18 to your computer and use it in GitHub Desktop.
memoized fibonacci function in Python
import datetime
def fib(a):
if (a>2):
return fib(a-1) + fib (a-2)
elif (a==1 or a==2):
return 1
elif (a<1):
return 0
def memoFibb():
fibs={}
def f(a):
if (fibs.has_key(a)):
return fibs[a]
elif (a>2):
fibs[a]=f(a-1)+f(a-2)
return fibs[a]
elif (a==1 or a==2):
return 1
elif (a<1):
return 0
return f
def timeProc(proc, arg):
sd=datetime.datetime.now()
print "start", sd
f=proc(arg)
sd2=datetime.datetime.now()
print "end", sd2
print "it took", sd2-sd
print "the answer is", f
"""
memoFibb runs many orders of magnitude faster than fib
>>> timeProc(memoFibb(),35)
start 2014-05-15 17:35:54.883773
end 2014-05-15 17:35:54.883773
it took 0:00:00
the answer is 9227465
>>> timeProc(fib,35)
start 2014-05-15 17:35:59.537773
end 2014-05-15 17:36:01.763773
it took 0:00:02.226000
the answer is 9227465
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment