5.factorial... No idea what to do



i get the error
Oops, try again. factorial(1) resulted in an error: maximum recursion depth exceeded

Replace this line with your code. 
def factor(n):
    if n > 1:
        answer = n * factor(n - 1)
    elif n < 1:
        answer = -n * factor(-n - 1)
    elif n == 0:
         answer = 1
        answer = 1
        return answer


The reason for that error is that you are calling your function inside your function. When you call factor, if the number is greater than one, you call factor, which calls factor, which calls factor, etc...


By definition, factorials are never negative, which means we cannot factorialize a negative number.

Even though a recursive function is possible for this exercise, we should instead seek to write an iterative function that does not use recursion.

The recursive is as follows:

def factorial(n):
    n = abs(n)     # prevent negative
    return 1 if n < 2 else n * factorial(n - 1)

Now try doing it with while or for.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.