Last active
August 29, 2015 14:01
-
-
Save ecounysis/5b81b09869dc654edb18 to your computer and use it in GitHub Desktop.
memoized fibonacci function in Python
This file contains hidden or 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
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