Try tracing the function with a pencil and paper. In this case, the print statement insde the function may be a bit misleading.
Consider this part of the program,
if(k>0):
result = k+tri_recursion(k-1)
...
From here,
tri_recursion(6) = 6 + tri_recursion(5)
So to get the result for tri_recursion(6)
we must get the result of tri_recursion(5)
Following this logic, the problem reduces to:
tri_recursion(6)
= 6 + tri_recursion(5)
= 6 + 5 + tri_recursion(4)
= 6 + 5 + 4 + tri_recursion(3)
= 6 + 5 + 4 + 3 + tri_recursion(2)
= 6 + 5 + 4 + 3 + 2 + tri_recursion(1)
= 6 + 5 + 4 + 3 + 2 + 1 + tri_recursion(0)
Now notice that 0 is not greater than 0 so the program moves to the body of the else clause:
else:
result = 0
...
Which means tri_recursion(0) = 0
. Therefore:
tri_recursion(6)
= 6 + 5 + 4 + 3 + 2 + 1 + tri_recursion(0)
= 6 + 5 + 4 + 3 + 2 + 1 + 0
= 21
Points to note
- In running this program.
k
is never equal to -1
, infact it is impossible.
- It is misleading to think of control flow in terms of "the compiler moving across a program". The compiler does't do anything during execution (JIT is a different matter). It is better to think in terms of control flow / order of execution in procedual languages, equationally in functional programming and relations in logic programming.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…