理解 Python 中的递归 [英] Understanding recursion in Python

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

问题描述

我真的想把我的大脑围绕在递归的工作原理上并理解递归算法.例如,下面的代码在我输入 5 时返回 120,请原谅我的无知,我只是不明白为什么?

I'm really trying to wrap my brain around how recursion works and understand recursive algorithms. For example, the code below returns 120 when I enter 5, excuse my ignorance, and I'm just not seeing why?

def fact(n):
    if n == 0:
        return 1
    else:
        return n * fact(n-1)

answer = int (raw_input('Enter some number: '))

print fact(answer)

推荐答案

让我们来看看执行过程.

lets walk through the execution.

fact(5):
   5 is not 0, so fact(5) = 5 * fact(4)
   what is fact(4)?
fact(4):
   4 is not 0, so fact(4) = 4 * fact(3)
   what is fact(3)?
fact(3):
   3 is not 0, so fact(3) = 3 * fact(2)
   what is fact(2)?
fact(2):
   2 is not 0, so fact(2) = 2 * fact(1)
   what is fact(1)?
fact(1):
   1 is not 0, so fact(1) = 1 * fact(0)
   what is fact(0)?
fact(0):
   0 IS 0, so fact(0) is 1

现在让我们收集我们的结果.

Now lets gather our result.

fact(5) = 5* fact(4)

用我们的结果代替 fact(4)

substitute in our result for fact(4)

fact(5) = 5 * 4 * fact(3)

用我们的结果代替 fact(3)

substitute in our result for fact(3)

fact(5) = 5 * 4 * 3 * fact(2)

用我们的结果代替 fact(2)

substitute in our result for fact(2)

fact(5) = 5 * 4 * 3 * 2 * fact(1)

用我们的结果代替 fact(1)

substitute in our result for fact(1)

fact(5) = 5 * 4 * 3 * 2 * 1 * fact(0)

用我们的结果代替 fact(0)

substitute in our result for fact(0)

fact(5) = 5 * 4 * 3 * 2 * 1 * 1 = 120

这就给你了.递归是将较大的问题视为成功的较小问题,直到达到微不足道(或基本")案例为止,从而将其分解的过程.

And there you have it. Recursion is the process of breaking a larger problem down by looking at it as successfully smaller problems until you reach a trivial (or "base") case.

这篇关于理解 Python 中的递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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