Explain Python Recursion like I'm 5 [duplicate]

一个人想着一个人 提交于 2019-12-23 06:13:36

问题


So I found this example of recursion in Python on W3 Schools, but am having trouble wrapping my head around it.

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)

The way I am reading it, with an initial input of 6, the first print of result should be 11. 6 + (6-1). What I'm struggling with i think is how the output is being calculated with the continual recursion of k-1 and what is happening here.

Can someone explain this to me as simply as possible?

Output:

Recursion Example Results
1
3
6
10
15
21

回答1:


The first call: tri_recursion(6) proceeds to the following line:

result = k + tri_recursion(k-1)

but it doesn't immediately return and proceed to the print(result).

Because a tri_recursion(k-1) call has been made, i.e. tri_recursion(5)

This proceeds to the same result line and launches a tri_recursion(4) call.

And so on until a tri_recursion(0) call is made, which returns 0, failing the if k > 0 check.

Now the deepest result = k + tri_recursion(k-1) which was made for k=1, receives the first returned value and computes the first result, which is 1, and prints it.

It then returns 1 to the tri_recursion(2) call which prints 3, and so on.




回答2:


Like a 5 year old

A guy wanted to know his seat row number so he asked the guy in front of him. This guy also did not know the answer so he asked the guy in front of him (convergence) and so on(recursion). Finally the question reached to the person sitting in first row (terminating condition).

Person in first row replies 1, the next guy adds one to it and replies 2 to the guy behind and so on until the first person gets the answer.

Ask
  Ask
    Ask
    I am 1
    Reply 1
  I am 2
  Reply 2
I am 3 (Aha moment)

Now apply this analogy to your code.

tri_recursion(6)
  tri_recursion(5)
    tri_recursion(4)
      tri_recursion(3)
        tri_recursion(2)
          tri_recursion(1)
            tri_recursion(0)
            return 0  (Only time in else part, the terminating condition)
          print 1 + 0
          return 1
        print 2 + 1
        return 3
      print 3 + 3
      return 6
    print 4 + 6
    return 10
  print 5 + 10
  return 15
print 6 + 15
return 21



回答3:


Does this help?

def tri_recursion(k):
  if(k>0):
    try_recursion_val = tri_recursion(k-1)
    result = k + try_recursion_val
    print(f"At k = {k}, we have tri_recursion(k-1) = {try_recursion_val}")
  else:
    result = 0
  return result

print("\n\nRecursion Example Results")
tri_recursion(6)

Recursion Example Results
At k = 1, we have tri_recursion(k-1) = 0
At k = 2, we have tri_recursion(k-1) = 1
At k = 3, we have tri_recursion(k-1) = 3
At k = 4, we have tri_recursion(k-1) = 6
At k = 5, we have tri_recursion(k-1) = 10
At k = 6, we have tri_recursion(k-1) = 15

so as you can see, what we are doing is repeatedly calling tri_recursion with increasing values of k (1 less than k).




回答4:


The reason you see output like this: to calculate result = k+tri_recursion(k-1) prior to print, function will call tri_recursion(k-1) — basically, the same function, but with different argument. And it will continue doing so, until it reaches call with k=0, where it returns, and chain of results propagates bottom-up.

So recursion idea overall is to have a stack of same functions with different context, and top calls (except for last one) actually waiting for last result, to propagate chain backwards.

I recommend looking into code visualization for non-familiar algos. I.e. http://www.pythontutor.com/visualize.html




回答5:


Recursion is a concept which is not natural in the way you would think but as soon as you wrap your head around it you will understand. :-)

The frist print out will be the one from the recursive call which is the furthest (technically the second-furthest) in the onion like structure of all the recursive calls. As soon as k counts down to 0 the function at the end returns 0 to the one above that so that one has the following operation:

result = 1+0
print(1)

It then returns result = 1 to the recursive call above it:

result = 2+1
print(3)

etc.




回答6:


when you call tri_recursion(k-1) every time it goes into if (k>0) until k=0. When in this case it going into else and working this piece of code:

else: result = 0 return result

and it returns result to prevoius called tri_recursion then happening something like that:

if(k>0): result = k+tri_recursion(k-1) # k=1 | tri_recursion(k-1) returned 0 | 1 + 0 = 1 print(result) # prints 1 and so on



来源:https://stackoverflow.com/questions/52925250/explain-python-recursion-like-im-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!