[英]How to prevent a recursion error implementing factorial in Python
I'm developing a math suite and am currently having issues implementing the recursive version of the factorial function.我正在开发一个数学套件,目前在实现阶乘 function 的递归版本时遇到问题。 The issue is when I use it in my Bayesian combination function:
问题是当我在我的贝叶斯组合 function 中使用它时:
C(n,k) = n! / k! * (n-k)!
I've tested it independently and it works as it should, but as soon as I put it in my combination function, I get the error Recursion Error: maximum recursion depth exceeded in comparison
, even for very small values of n and k.我已经独立测试过它并且它应该可以正常工作,但是一旦我将它放入我的组合 function 中,我就会收到错误
Recursion Error: maximum recursion depth exceeded in comparison
,即使对于非常小的 n 和 k 值。
I've implemented an iterative solution which works perfectly, so why do I keep getting a recursion error?我已经实现了一个完美运行的迭代解决方案,那么为什么我不断收到递归错误?
Here's the recursive implementation:这是递归实现:
def factorial(n):
if n == 1 or n == 0:
return n
else:
return n * factorial(n - 1)
Here's the iterative implementation:这是迭代实现:
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
And they are used in the combination function like so:它们在 function 组合中使用,如下所示:
def combination(n, k):
result = factorial(n) / (factorial(k) * factorial(n - k))
return result
The recursive function seems to work only when k = 1.递归 function 似乎仅在 k = 1 时才有效。
Here are some sample outputs which produces the recursion error:以下是一些产生递归错误的示例输出:
combination(2,1) = 2
combination(2,2) =
Traceback (most recent call last):
File "baysian.py", line 44, in <module>
answer = combination(n, k)
File "baysian.py", line 18, in combination
result = factorial(n) / (factorial(k) * factorial(n - k))
File "baysian.py", line 9, in factorial
return n * factorial(n - 1)
File "baysian.py", line 9, in factorial
return n * factorial(n - 1)
File "baysian.py", line 9, in factorial
return n * factorial(n - 1)
[Previous line repeated 994 more times]
File "baysian.py", line 6, in factorial
if n == 1:
RecursionError: maximum recursion depth exceeded in comparison
It turns out that my recursive factorial implementation was incorrect.事实证明,我的递归阶乘实现是不正确的。 It would return 0 for.0 instead of 1. I've added some changes and now it works.
它将返回 0 for.0 而不是 1。我添加了一些更改,现在它可以工作了。 Here's my revised solution.
这是我修改后的解决方案。
def factorial(n):
if n == 1:
return n
elif n == 0:
return 1
else:
return n * factorial(n - 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.