0

Recently I came upon some code on a Python tutorial for recursion, it is a basic factorial recursion:

def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
    return 1
else:
    res = n * factorial(n-1)
    print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
    return res  
print(factorial(5))

This is the console output:

factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for  2  * factorial( 1 ):  2
intermediate result for  3  * factorial( 2 ):  6
intermediate result for  4  * factorial( 3 ):  24
intermediate result for  5  * factorial( 4 ):  120
120

After doing some research, I feel like I have an understanding of why this is the output but I wanted to make sure. From my understanding:

it repeats the else statement 4 times and puts the n value and res value into a call stack. When res calls factorial(1), it goes to the base case and stops the recursion so we can retrieve the stack data. It pops n =1 and doesn't print any output, but then pops 2,3,4,5 and retrieves their res values that were calculated during recursion. Finally once res is returned enough, we are left with 5*24(n*res) on the top of the stack and Python knows that's the value to return for the print(factorial(5)).

Is this all correct information, am I missing something? Please let me know if any of this is incorrect or point me in a direction of some resources that can clarify this. Thank you!

1 Answer 1

2

Yes, you are right.

Notice how factorial(n-1) is called before

print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)

That's why you first get the "factorial has been called" print messages before the`"intermediate result" prints.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.