5.factorial... No idea what to do


#1


https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/5?curriculum_id=4f89dab3d788890003000096#

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
    else:
        answer = 1
        return answer


#2

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...


#3

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.


#5

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