Home > Software design >  Can somebody explain me this recursion?
Can somebody explain me this recursion?

Time:06-24

def name(n):
    if n>0:
      name(n-1) 
      name(n-1)
      print(n)
      
name(5)

How this is generating 1,1,2,1,1,2,3.....so on output? like which function is working first or both working simultaneously and how n is printing like this.

CodePudding user response:

Try with smaller numbers. For example if you run name(1) it will just print 1. becase two functions in the middle will just return. If you write name(2) it will run the first inner funtion, which will print 1(like I said previously). Second function will do the same and last statement will print 2. So the output is 1 1 2. If you go for name(3) it will just the same as name(2) but twice and will print 3 at the end (1 1 2) (1 1 2) 3. name(4) will do name(3) twice and print 4 at end and so on

CodePudding user response:

Hello I attached this image that shows explanation in details enter image description here

  • Related