python - 有人可以描述这部分是如何工作的“结果= 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 还是我弄错了?
谢谢你的帮助。如果这是一个白痴问题,再次抱歉。
解决方案
例如,首先你用 5 调用函数,然后你会再次用 5 调用它并相乘,它会溢出递归限制和无限循环。
因此,您需要递减 1,然后调用 4、3 等等,当它小于 2 时返回 1。
推荐阅读
- jenkins - 有没有办法从 GitLab webhook 中获取 Jenkins 中的 HTTP 请求信息?
- python - 在不使用阈值的情况下过滤掉时间序列的一部分
- amazon-web-services - 通过 API-Gateway 在 S3 上访问 Webapp(HTML、JS、CSS)
- ssl - npm UNABLE_TO_VERIFY_LEAF_SIGNATURE Verdaccio
- arrays - 如何在 MongoDB 聚合中查询数组以获取 AND 和 OR 的不同组合?
- ios - NSFetchedResultsController 没有持续更新
- react-native - 如何使用 Expo 解决“重复的模块名称:react-native”
- raspberry-pi3 - 如何将另一个树莓派作为设备连接到 Greengrass 组并相互通信?
- python-3.x - 如何添加列表索引给出的数字?
- django - Django将html路径引用到另一个目录