Search code examples
pythonrecursioncombinationsfactorial

maximum recursion depth exceeded in comparison


I wrote this piece of code to compute the number of combinations:

def fact(n):
    return 1 if(n == 1) else n * fact(n - 1)

def combinations(n,k):
    return fact(n)/((fact(n - k) * fact(k)))

while(True):
    print(combinations(int(input()), int(input())))

The factorial function seems to work fine. But why does it give me a maximum recursion depth exceeded in comparison error when I try to find the combinations of two numbers? Is there something wrong with the factorial function, since that's where the error seems to be originating from?

This was the error I got:

builtins.RuntimeError: maximum recursion depth exceeded in comparison


Solution

  • Try to replace:

    def fact(n):
        return 1 if(n == 1) else n * fact(n - 1)
    

    to:

    def fact(n):
        return 1 if(n <= 1) else n * fact(n - 1)
    

    Because if you pass 2 identical numbers, you would try to compute fact(0) (which would call fact(-1) and fact(-2), etc until the maximum recursion depth error).