Home > Back-end >  I don't understand how this recursive function works
I don't understand how this recursive function works

Time:02-02

So these are the examples I got:

def bottom_up(n):
    if n == 0:
        pass
    else:
        bottom_up(n-1)
        print(n)

and this one, which is fine:

def top_down(n):
    if n == 0:
        pass
    else:
        print(n)
        top_down(n-1)

I have an understanding of recursion, so that isn't the problem. My problem is the result for bottom_down():

bottom_up(5)
1
2
3
4
5

I've asked other students and my teacher(math teacher, because my school won't hire a computer science teacher since I'm the only one doing computer science), and I don't know what to search on google.

CodePudding user response:

I highly encourage you to walk through the functions yourself to see how it works, but the difference is in the order of the print statement and the recursive call. The first function has the recursive call before the print statement, so that means it has to go down to the base case in order to start printing the numbers. This means it will start at the smallest number and go up and back to the starting number. The second function has the print statement before the recursive call, which means that it will print the number then take a step closer to the base case. Once the base case is reached, the recursive calls go back up, and exit as there is nothing after them. Hope this helped.

CodePudding user response:

Pass is a placeholder for code. Need more context in what you are trying to do.

bottom_up(5) is looping So before bottom_up(5) prints 5 it will run the function bottom_up(4), bottom_up(3), bottom_up(2), bottom_up(1), bottom_up(0) and so on.... bottom_up(0) and and negative n will pass and not print anything.

So the first thing to print will be bottom_up(1) then bottom_up(2) and so on until 5.

  • Related