我真的在努力思考递归的工作原理并理解递归算法。例如,当我输入 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/