Python 递归函数如何用于 tri_recursion 函数? [英] How does a Python recursive function works for tri_recursion function?

查看:85
本文介绍了Python 递归函数如何用于 tri_recursion 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,我发现了下面的递归程序 难以遵循.在调试程序时,我发现它经历了递归,每次递归时 k 的值都会递减 -1.在某一时刻 k 为 -1,编译器移动到 else 部分并返回 0.

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.

最后,k 的值变成了 1,这是怎么回事?

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("\n\nRecursion Example Results")
tri_recursion(6)

和输出:

Recursion Example Results  
1  
3  
6  
10  
15  
21  

推荐答案

尝试用铅笔和纸描摹函数.在这种情况下,函数中的打印语句可能有点误导.

Try tracing the function with a pencil and paper. In this case, the print statement insde the function may be a bit misleading.

考虑程序的这一部分,

if(k>0):
    result = k+tri_recursion(k-1)
...

从这里开始

tri_recursion(6) = 6 + tri_recursion(5)

所以要得到tri_recursion(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)

现在注意 0 不大于 0,所以程序移动到 else 子句的主体:

Now notice that 0 is not greater than 0 so the program moves to the body of the else clause:

else:
    result = 0
...

这意味着 tri_recursion(0) = 0.因此:

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

注意事项

  1. 在运行这个程序时,k 永远不等于 -1,事实上这是不可能的.
  2. 从编译器在程序中移动"的角度来考虑控制流是一种误导.编译器在执行期间不做任何事情(JIT 是另一回事).最好从过程语言中的控制流/执行顺序、函数式编程中的等式和逻辑编程中的关系方面进行思考.
  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.

这篇关于Python 递归函数如何用于 tri_recursion 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆