I thought I understood recursive functions but realised I don’t actually understand what is happening under the bonnet
Running this Python code to generate the Fibonacci series gives the expected values
def fib(k):
result = 0
if(k > 0):
result = k + fib(k - 1)
print(f'after call k is {k} and result is {result}')
else:
print()
return result
#return k
print("Recursion Example Results")
fib(6)
And this is what it returns:
Recursion Example Results
after call k is 1 and result is 1
after call k is 2 and result is 3
after call k is 3 and result is 6
after call k is 4 and result is 10
after call k is 5 and result is 15
after call k is 6 and result is 21
But if I change the code to return k:
def fib(k):
result = 0
if(k > 0):
result = k + fib(k - 1)
print(f'after call k is {k} and result is {result}')
else:
print()
#return result
return k
print("Recursion Example Results")
fib(6)
I get this:
Recursion Example Results
after call k is 1 and result is 1
after call k is 2 and result is 3
after call k is 3 and result is 5
after call k is 4 and result is 7
after call k is 5 and result is 9
after call k is 6 and result is 11
Why the difference and how is it calculating this? Why is it not returning k = 1,2,3,4,5,6?
JonP is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5
In fib(k + 1)
, the return value of fib(k)
is used.
Therefore it matters whether fib(k)
returns k
or result
.
When you are returning k then result becomes result = k + k - 1
and when you are returning result it performs Additition of all the number in decreasing order, like for 6 it will be 6+5+4+3+2+1
1