Just read an interesting blog post about comparing Python and Haskell code to calculate the Fibonacci sequence. I wrote a faster version, just for the hell of it. I realise that it is not a fair comparison any more, and doesn’t prove anything, but it does demonstrate a useful optimization technique. Here’s the code…
from time import time
def memoize(f):
f._cache = {}
def do_f(n):
if n in f._cache:
return f._cache[n]
r = f(n)
f._cache[n] = r
return r
return do_f
@memoize
def fib(n):
if n == 0 or n == 1:
return n
else:
return fib(n-1) + fib(n-2)
if __name__ == "__main__":
start_time = time()
for i in range(36):
print "n=%d => %d" % (i, fib(i))
print "Time elapsed: %f" % (time() - start_time)
When I run it on my machine, it claims to take 0.00000 seconds. Damn, thats fast!