Python, Make an iterative function into a recursive function

  • A+
Category:Languages

I've created an iterative function which outputs 4 3 2 1 0 1 2 3 4.

def bounce2(n):     s = n     for i in range(n):         print(n)         n = n-1      if n <= 0:         for i in range(s+1):             print(-n)             n = n-1     return bounce2(4) 

If I want a recursive function that does the exact same thing, how should I think?

 


Try this:

def bounce(n):     if n >= 0:         print(n)         bounce(n - 1)          if n:             print(n)  bounce(4) 

the output will be: 4 3 2 1 0 1 2 3 4

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: