For example, the code in textbook — solving Fibonacci problem by using recursion — is like this:
cache = {}
def fibo(n):
if n in cache :
return cache[n]
elif n <=2:
cache[n] = 1
else:
cache[n] = fibo(n-1) + fibo(n-2)
return cache[n]
However, i am concerned every time doing function calls, costs are needed. Why didn’t the textbook use this code instead, to avoid unnecessary function call:
cache = {}
def fibo(n):
if n <=2:
cache[n] = 1
else:
# to avoid unnecessary function call
if n-1 in cache:
f1 = cache[n-1]
else:
f1 = fibo(n-1)
if n-2 in cache:
f2 = cache[n-2]
else:
f2 = fibo(n-2)
cache[n] = f1 + f2
return cache[n]
In this way, we could avoid unnecessary function call before actually calling it.
Anyway, my question is, why don’t the authors of the textbook write the code in the second way?
What you’re describing is dynamic programming. You’re using an array to store the steps of recursion, ala memoization. For something like Fibonacci, where there is more than one recursive call per iteration, dynamic programming is indeed the preferred technique.
As for why the textbook showed you the code it did, most likely because the authors wanted to just demonstrate recursion without going into too many concepts at once.