简体   繁体   中英

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. The issue is when I use it in my Bayesian combination 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.

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:

def combination(n, k):
    result = factorial(n) / (factorial(k) * factorial(n - k))
    return result

The recursive function seems to work only when 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

From this page:

import sys
print(sys.getrecursionlimit())

Then adjust with:

sys.setrecursionlimit(<number>)

Will crash your machine if you enter a number too high

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. Here's my revised solution.

def factorial(n):
    if n == 1:
        return n
    elif n == 0:
        return 1
    else:
        return n * factorial(n - 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM