maximum recursion depth exceeded in comparison

后端 未结 6 1910
故里飘歌
故里飘歌 2021-01-06 13:21

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):
    retur         


        
6条回答
  •  抹茶落季
    2021-01-06 14:01

    You should try to avoid recursion for such a simple function as the factorial of a number. Recursion is really powerful, but sometimes it is overused for no reason.

    Here is the code for the iterative version of factorial function:

    def fact(n):
        result = 1
        for i in range(2, n + 1):
            result *= i
        return result
    

    Notice what Maxime says in the previous answer, that is exactly the problem you are having: your function doesn't contemplate the factorial of 0.

提交回复
热议问题