I don't understand how this recursive function works

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.

>Solution :

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.

Leave a Reply