首页 > 解决方案 > 有人可以描述这部分是如何工作的“结果= n阶乘(n-1)”

问题描述

如果这是一个愚蠢或重复的问题,我深表歉意。我已经学习 python 大约 2 周了,我一直遇到循环的小问题。例如。

def factorial(n):

      if n < 2:       # I understand once the number becomes < than 2 the loop continues
        return 1.  #and here we return the value 1
     result = n * factorial(n-1)    #why do we subtract 1 from n?
     return result 
factorial(5) #my random number

我很难理解为什么要从 n 中减去 1。你不应该加 1 来包含数字吗?

在我看来,它看起来像这样: result = n(1) * factorial((1)-1) # doesn't n stay = to 1 还是我弄错了?

谢谢你的帮助。如果这是一个白痴问题,再次抱歉。

标签: pythonmathfactorial

解决方案


例如,首先你用 5 调用函数,然后你会再次用 5 调用它并相乘,它会溢出递归限制和无限循环。

因此,您需要递减 1,然后调用 4、3 等等,当它小于 2 时返回 1。


推荐阅读