Search code examples
pythonfunctionrecursionmemoryreturn-value

Does return keyword in Python saves the value in memory for a function with an specific parameter?


I'm learning about recursive functions, and I have a doubt, let's say:

def fibonacci(n):
if n == 0 or n == 1:
    return 1

return fibonacci(n-1) + fibonacci(n-2)

fibonacci(4)
fibonacci(5)

When the program executes fibonacci(5), which would be like:

fibonacci(5) = fibonacci(4) + fibonacci(3)

Does Python have to calculate again the last two functions using recursion, or would it have the result already saved in memory as it already executed the same function with those same parameters when it executed fibonacci(4) and so would instantly assign them their values?


Solution

  • First off, there is no automatic caching for function calls in Python. If you call fibonacci(6) and then fibonacci(5), Python will call all of the associated functions once more, even though it is redundant.

    What you are talking about (caching and such) is called memoization and is the foundational principle of a larger concept called Dynamic Programming. DP is basically a way of taking a basic recursion (like your fibonacci implementation) and making it more efficient by applying some techniques (like caching)

    Here is a pretty good website that explains this concept pretty well and actually uses the fibonacci series as an example. What is Dynamic Programming