I am trying to figure out recursion and how it operates and I cant seem to figure out what is happening in this code.
def printFun(test):
if (test < 1):
return
else:
print(test, end="a ")
printFun(test-1) # statement 2
print(test, end="n ")
return
# Driver Code
test = 3
printFun(test)
This outputs
3a 2a 1a 1n 2n 3n
I can make sense of the first 4 outputs. test = 3, which not less than 1, so print test(1a), then re-call the printFun function with test-1 being 2, which is not less than 1, so print test (2a), then (1a) then 0, which IS less than 1 so return. I assume this brings you back to the
print(test, end='n')
line? which now prints 1n.
This is where I am left perplexed... what is happening beyond this??? How does it start ascending and then stop again at 3? What is the flow and logic of this? Sorry if this is a ridiculous question and I am overlooking something blatantly obvious.
But I cannot wrap my mind around this... Anyone?
Thanks!
CodePudding user response:
Its because the stack unwinds depth first. In pseudocode, with each indentation being a new call to the function, you get
call printFun(3)
print 3a
call printFun(2)
print 2a
call printFun(1)
print 1a
call printFun(0)
print nothing
return
(test still = 1 in this frame)
print 1n
return
(test still = 2 in this frame)
print 2n
return
(test still = 3 in this frame)
print 3n
return
When you return from the most recently called printFun
, you get back to an older set of local variables holding the older value.
CodePudding user response:
You call printFun
three times and each of it prints twice, so we should have 6 prints, isn't it?
Sometimes it's hard to unsolve recursion but it doesn't differ as calling another function:
def foo():
print("before")
other_foo()
print("after")
Do you agree everything that is printed by other_foo
will be between "before" and "after"? It's the same case, you could write it that way:
def printFun1():
print("1a")
print("1n")
def printFun2():
print("2a")
printFun1() # it prints "1a" and "1n" between "2a" and "2n"
print("2n")
def printFun3():
print("3a")
printFun2()
print("3n")
printFun3()