0
Help me understand recursion please
Example 1: def fun(a): if a > 30: return 3 else: return a + fun(a + 3) print(fun(25)) Example 2: def fun(a): if a > 30: return 3 else: return a + fun(a + 3) print(fun(20)) ____________________________________ Why is example 1 as easy as 3 + 25 + 3 + 25 to get the answer 56 but the same method doesn’t apply for example 2. I get the output 101 instead of what I thought would be 46.
2 Respostas
+ 2
Follow through the if statement in stacks and you get;
20 + (20 + 3) + (23 + 3) + (26 + 3) + (29 + 3) + 3
0
The 2nd program works as follows:
It first calculates fun(20):
return 20 + fun(23)
|	Now the program calculates fun(23):
|	return 23 + fun(26)
|	|	Now it calculates fun(26):
|	|	return 26 + fun(29)
|	|	|	Now it is fun(29):
|	|	|	return 29 + fun(32)
|	|	|	|	fun(32) returns 3 directly
|	|	|	return 29 + 3
|	|	return 26 + 32  (because fun(29) = 32)
|	return 23 + 58  (because fun(26) = 58)
return 20 + 81  (because fun(23) = 81)



