4 ms·
I like to use dicts for memoization...This runs about 8% faster on my machine than OP's solution: memo5 = {0:0,1:1} def fib_mem5(n): try:
by randlet 15y ago
I like to use dicts for memoization...This runs about 8% faster on my machine than OP's solution:
memo5 = {0:0,1:1}
def fib_mem5(n):
try:
return memo5[n]
except KeyError:
memo5[n] = fib_mem5(n-1)+fib_mem5(n-2)
return memo5[n]
Note: the above version runs faster than the cleaner:
memo6 = {0:0,1:1}
def fib_mem6(n):
if n in memo6:
return memo6[n]
memo6[n] = fib_mem6(n-1)+fib_mem6(n-2)
return memo6[n]
- infinitegalaxy 15y agoHow much faster? As you stated, the second version is much cleaner; I'd prefer to use it if it isn't that much of a performance hit. Edit: hm, in my casual testing, the 'cleaner' version takes about 10% longer.