Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

recursion - How does a Python recursive function works for tri_recursion function?

I'm new to Python, I found the below recursive program being tough to follow. While debugging the program I could find that it goes through recursion and the value of k decrements -1 every time we recurse. At one point k is -1 and the compiler moves to the else part and returns 0.

Finally, the k value turns out to be 1, how does this happen?

def tri_recursion(k):
  if(k>0):
    result = k+tri_recursion(k-1)
    print(result)
  else:
    result = 0
  return result

print("

Recursion Example Results")
tri_recursion(6)

And the output:

Recursion Example Results  
1  
3  
6  
10  
15  
21  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

  1. In running this program.k is never equal to -1, infact it is impossible.
  2. 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...