Home > Software design >  Why does this recursion return 0?
Why does this recursion return 0?

Time:09-17

def bounce(n):
    if n < 1: 
        return 0 #if I change this value to 1 n gets printed out correctly, why?
    else:
        return n * bounce(n - 1)


print(bounce(5))

CodePudding user response:

Your base case is return 0. After the line return n * bounce(n - 1) where n is 1, bounce(0) will be executed, returning 0 and multiplying all your previous results by 0.

Following the calls, we see:

  • 5>=1, so return 5*bounce(4)
  • 4>=1, so return 5*4*bounce(3)
  • 3>=1, so return 5*4*3*bounce(2)
  • 2>=1, so return 5*4*3*2*bounce(1)
  • 1>=1, so return 5*4*3*2*1*bounce(0)
  • 0<1, so return 5*4*3*2*1*0

meaning everything gets zeroed out at the end. You want the base case to be 1 for that reason.

CodePudding user response:

You sould add an check that returns the value for 0. Otherwise you recursion multiplys with 0 at the final call of the recursiv function.

def bounce(n):
   if n < 1:
      return 0
   elif n == 1:
      return 1
   else:
       return n * bounce(n - 1)

CodePudding user response:

This recursion is returning 0 because when n = 1 your compiler goes inside else block and calls return 1 * bounce(0) and this time compiler return 0 cause if condition is satisfied here. If you want your output to be 120 (in this case ) you can change your code like this :

def bounce(n):
        if n < 1: 
            return 0
        else :
            if n == 1:
                return n ;
            return n * bounce(n - 1)
    print(bounce(5))

CodePudding user response:

Yes, you have a loop that will continually repeat until you get to the point that n = 0, and you are printing a product where at least one value has "n * 0" in it.

  • Related