I have a Python program that performs pretty fast for fibonacci sequences up to 999. For numbers above 999, the program fails with RecursionError: maximum recursion depth exceeded in comparison
. I am utilizing memoization to cache fibonacci of previous values.
Here is my code.
def fibonacci(position, cache=None):
if cache is None:
cache = [None] * (position + 1)
if cache[position] is not None:
return cache[position]
else:
if position < 3:
return 1
else:
cache[position] = fibonacci(position - 1, cache) + fibonacci(position - 2, cache)
return cache[position]
Does anyone have a hint how I can improve my solution?