Recursion, a bit confused

Hi,

Please help me understand this better, I’m having a hard time understanding the output from this portion of the code:

result = k+tri_recursion(k-1)

Is this portion of the code saying K plus the function tri_recursion(K subtract 1 from K)?

The function is below and the output - this example came from w3schools.com I hope it okay to reference other learning materials.

Here’s the code:

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)

Code Output:

C:\Users\My Name>python demo_recursion.py

Recursion Example Results
1
3
6
10
15
21

Please help.

Recursion is an abstract concept, the only way I could visualize the process is by writing this:

tri_recursion(6)
                                                                                                     
6 + tri_recursion(5)                         6 + 15 = 21
	5 + tri_recursion(4)                     5 + 10 = 15                  
		4 + tri_recursion(3)                 4 + 6 = 10      
			3 + tri_recursion(2)             3 + 3 = 6         
				2 + tri_recursion(1)         2 + 1 = 3     
					1 + tri_recursion(0) <- but here k = 0, so 1 + tri_recursion(0) = 1 + 0 = 1

Also this might make it more clear.. i know, it's tough and mind boggling.

tri_recursion(1) = 1 + tri_recursion(0) = 1 + 0  = 1
tri_recursion(2) = 2 + tri_recursion(1) = 2 + 1  = 3
tri_recursion(3) = 3 + tri_recursion(2) = 3 + 3  = 6
tri_recursion(4) = 4 + tri_recursion(3) = 4 + 6  = 10
tri_recursion(5) = 5 + tri_recursion(4) = 5 + 10 = 15
tri_recursion(6) = 6 + tri_recursion(5) = 6 + 15 = 21

Important to note the value of k keeps decrementing when called recursively.
It’s easier to visualize by working your way down on the left side, and then work your way back upward on the right side.
Maybe someone can help out to explain it more clearly.

1 Like

great I was very confused but now it is clear