Skip to content

Instantly share code, notes, and snippets.

@hltbra
Created November 22, 2012 18:18
Show Gist options
  • Select an option

  • Save hltbra/4132445 to your computer and use it in GitHub Desktop.

Select an option

Save hltbra/4132445 to your computer and use it in GitHub Desktop.
fibonacci com memoizatino
import timeit
def memoize(fn):
cache = {}
def newfn(arg):
if arg in cache:
return cache[arg]
else:
cache[arg] = fn(arg)
return cache[arg]
return newfn
def fib(n):
if n in (1, 2):
return 1
return fib(n - 1) + fib(n - 2)
def fast_fib(n):
if n in (1, 2):
return 1
return fast_fib(n - 1) + fast_fib(n - 2)
fast_fib = memoize(fast_fib)
if __name__ == '__main__':
print timeit.timeit("import fib; fib.fib(35)", number=1)
print timeit.timeit("import fib; fib.fast_fib(35)", number=1)
# 3.71057915688
# 0.000109195709229
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment