Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 13 Online
OpenStudy (anonymous):

Can someone explain in details the flow of execution of this code below. def factorial(n): if n == 0: return 1 else: recurse = factorial(n-1) result = n * recurse return result Well assuming you call the function factorial(3), what is the value of 'recurse' and when does the result expression starts its execution in the else statement? And then what is the value of result after each call?

OpenStudy (anonymous):

factorial(n) steps: 1. Jump into factorial(3) 2. Jump into factorial(2) 3. Jump into factorial(1) 4. Jump into factorial(0) 5. factorial(0) returns 1 back to the code at factorial(1). 6. factorial(1) n = 1. recurse = 1. and use it to return result (1*1 = 1) to factorial(2). 7. factorial(2) n = 2. recurse = 1 and use it to return result (2*1 = 2) to factorial(3). 8. factorial(3) n = 3. recurse = 2. and use it to return the FINAL result (3*2 = 6). It can be very confusing to "think" this! To figure this out (for example at a test), it might be best to just draw out every. single. step. with the responding values. Just make sure you MASTER the "order" of which the programming events happens. If you don't know the order (going in and out of methods), you will have problems! :)

OpenStudy (anonymous):

Ohh @Ivanskodje thanks alot!!!! You the bomb!!!!

OpenStudy (anonymous):

But i still have 2 questions @Ivanskodje! After step5, why does it jump to Factorial(1)? I was thinking it has to go to Factorial(3) which was the initial call to start executing the remainder of the else statement. Then the second question is this: How come about the recurse value in each of Step6 to Step8?

OpenStudy (puzzler7):

At step 4, you have 4 layers of factorial(n). You have to work your way backwards through them. Think of building then destroying a tall building. You don't want it to come crashing down, so you destroy the top floor, then the one below that, then the one below that, and so on.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!