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

查看:84
本文介绍了了解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)


推荐答案

让我们逐步执行。

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)

用结果代替事实(4)

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

替换为我们对事实(3)的结果

substitute in our result for fact(3)

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

用我们的结果代替事实(2)

substitute in our result for fact(2)

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

用我们的结果替换为事实(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天全站免登陆