python - 理解 Python 中的递归

标签 python algorithm python-2.7 recurrence induction

我真的在努力思考递归的工作原理并理解递归算法。例如,当我输入 5 时,下面的代码返回 120,请原谅我的无知,我只是不明白为什么?

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

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

print fact(answer)

最佳答案

让我们来看看执行过程。

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

现在让我们收集结果。

fact(5) = 5* fact(4)

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

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

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

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

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

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

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

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

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

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

就是这样。递归是通过将大问题视为成功的小问题来分解大问题的过程,直到您达到一个微不足道的(或“基本”)情况。

关于python - 理解 Python 中的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11693819/

相关文章:

Python2 : Difference between print and print() with '\r' escape character

Python:将字符串转换为其二进制表示形式

python - 使用 pytest 进行惰性参数化

python - 我可以使用哪些 Python 工具来编写受密码保护的网页的抓取工具?

python - 从 Pandas 数据框索引创建列

algorithm - 经济模拟算法?

python - Sympy:用符号玻色子交换代替其数值

algorithm - 堆排序算法

algorithm - 从坐标列表和连接它们的边列表创建一个 k-ary 树。

arrays - NumPy 加速设置二维数组的元素