We have this recursive python program:
def tri_recursion(k):
if(k > 0):
result = k tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
As per my understanding the output of this program should have been:
1,3,5,7,9,11
But the actual output is:
1,3,6,10,15,21
Can someone explain the reasoning behind it? This is my understanding program will start as
k as 6, then 6 > 0 then system will call tri_recusrion(6-1)
now k is 5, then 5 > 0 then system will call tri_recusrion(5-1)
now k is 4, then 4 > 0 then system will call tri_recusrion(4-1)
now k is 5, then 3 > 0 then system will call tri_recusrion(3-1)
now k is 2, then 2 > 0 then system will call tri_recusrion(2-1)
now k is 1, then 1 > 0 then system will call tri_recusrion(1-1)
now k is 0, then 0 !> 0 condition will break
now function will start to return in reverse order:
tri_recusrion(1-1) in this case k is 1; k (1-1) prints 1
tri_recusrion(2-1) in this case k is 2; k (2-1) prints 3
tri_recusrion(3-1) in this case k is 3; k (3-1) prints 5
tri_recusrion(4-1) in this case k is 4; k (4-1) prints 7
tri_recusrion(5-1) in this case k is 5; k (5-1) prints 9
tri_recusrion(6-1) in this case k is 6; k (6-1) prints 11
CodePudding user response:
Let me first explain what this function does:
k
is the argument of the function, the base condition is when k
is 0, result is 0 and nothing is printed, function just returns 0
If k
is greater than 0, the program calculates tri_recursion(k-1
), adds it to the k
and prints it then returns it
If we call the function with argument k=6
, it will call the same function with k=5
, then it does the same with k=4
... and finally call itself with k=0
and program will stop calling itself. After that point calculated result will be carried to the call one level before to finalize that call.
Thus, the steps to execute right after program reach k=0
are as follows.
Since k=0
returns 0
, result of k=1
becomes k 0
=> 1 0
, prints 1
and returns it
Since k=1
returns 1
, result of k=2
becomes k 1
=> 2 1
, prints 3
and returns it
Since k=2
returns 3
, result of k=3
becomes k 3
=> 3 3
, prints 6
and returns it
Since k=3
returns 6
, result of k=4
becomes k 6
=> 4 6
, prints 10
and returns it
Since k=4
returns 10
, result of k=5
becomes k 10
=> 5 10
, prints 15
and returns it
Since k=5
returns 15
, result of k=6
becomes k 15
=> 6 15
, prints 21
and returns it
CodePudding user response:
Each time the function is called by itself, it adds the current value of k
to result
. The current list that you're printing is 1, 1 2, 1 2 3, 1 2 3 4, ...
, which is also 1, 3, 6, 10, ...
. To fix the error, write result = 1
and result = 2 tri_recursion(k - 1)
instead of result = 0
and result = k ...
, respectively.