5. factorial


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

print factorial(5)

how does "x * factorial(x-1)" loops itself down to one and times them all together? Could you explain?
Thanks.


#2

I'm not sure if I understood your question right. If your function is not working you should try to indent all lines below the first one.

Oh I think I got your question now. It's a recursive function (function within a function) which iterates through the function until 1 because you defined the function to do something else if x == 1 .......


#3

Wel this calculates the factorial using 2 assumptions first 1! and 0! are 1 actually you only need one of them. And the other is that n! is n*(n-1)!. Which you can easily see 6! = 6*(5*4*3*2*1) = 6*5!

So what it does is something like this:

(5!) = (5*(4!)) = (5*(4*(3!))) = (5*(4*(3*(2!)))) = (5*(4*(3*(2*(1!))))) = (5*(4*(3*(2*(1)))))
Where (n!) indicates a function call which is in the next step replaced by it's result. Once you've reached the base case for 1 you go back:
(5*(4*(3*(2*(1))))) = (5*(4*(3*(2*1))))) = (5*(4*(3*(2)))) = (5*(4*(6))) = (5*(24)) = (120) = 120