Ask Your Question

Revision history [back]

Your code is probably not well copied since the function f directly returns something, so what is after that will never be executed.

Anyway, here is an example on how to memoize a recursive function:

sage: @cached_function
....: def fibo(n):
....:     if n == 0 or n == 1:
....:         return 1
....:     else:
....:         return fibo(n-1) + fibo(n-2)

You can see the difference by calling fibo(100) with and without the @cached_function decorator.

Now, if you want to compute, say, fibo(1000), you may encounter a RuntimeError: maximum recursion depth exceeded. So the trick is to fill the memory in the right order:

sage: for i in range(1000):
....:     a = fibo(i)
sage: fibo(1000)