Factorial


#1



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

Hi, so I want to calculate the factorial of a number. I thought best way is to take the number in a loop, and every loop reduce it by 1 and put those numbers in a list.
After that multiply the components of the list with reduce

But its giving me this error: Oops, try again. factorial(1) returned 0 instead of 1

def factorial(x):
    mult = [x]
    for i in range(x):
        mult.append(i)
        x = x - 1
    fact = reduce(lambda b, a: a*b, mult)
    return fact


I don't understand, please can someone explain this to me :frowning:


#2

There's no reason to loop through the number.

Try something like this:

def factorial(x):
    if x == 1:
        return 1
    else:
        return x * factorial(x - 1)

#3

Wow that is so smart :smiley: thank you
I always overthink the questions and do way too many steps


#4

I too am guilty of overthinking things. But once you get the hang of certain commands, you'll get better at knowing when and when not to use them.


#5

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