Tail Recursion
Recursion means defining something in terms of itself. When we take a problem we can divide it into different parts or sub problems. To solve each of those sub problems we can call the functions. In recursion, inside the function we use the same function over and over again.
The tail recursion is a special case of recursion.In this there is no computations after the recursive call. In the function the recursive call should be the final instruction.The recursive call is not compose with reference to the memory cells. In normal recursion, the computer has to remember the return address but in tail recursion it does not need to do so. After the recursive call it does not have to any performance, so it immediately return the calling function. Because of that tail recursion improves the efficiency. The following examples will explain the above explanations clearly.
Normal recursion
def multiple(n):
if n==1:
return 1
else:
return n*multiple(n-1)
print(multiple(4))
This will execute as follows.
4*(multiple(3))
4*(3*multiple(2))
4*(3*(2*multiple(1)))
4*(3*(2*(1)))
24
From the above example you can clearly see that after calling the recursive call it has done some calculations.
Tail recursion
def multiples(n,rec=1):
if n==1:
return rec
else:
return multiples(n-1, rec*n)
print(multiples(4,1))
This will execute as follows.
multiples(4,1)
multiples(3,1*4)
multiples(2,4*3)
multiples(1,12*2)
24
In this way also it gives the same answer.After the recursive call it had not done any calculations , it had simply deliver the answer we needed.
The benefits of tail recursion are efficiency , readability, etc