educative.io

Doubt on the following problem

def rec_count (number):
print (number)

Base case

if number == 0:
return
rec_count (number - 1) # A recursive call with a different argument
print (number)

rec_count (5)

=================================================================

In the above program, at one point, rec_count(0) is called recursively. In this call, we first print the number as ‘0’ then we go to the line below,

if number == 0,
return

In the above line the condition is fulfilled, hence ‘None’ is returned.

I am not able to understand how after that

1
2
3
4
5

is printed ?

I have paid for the course and the doubt posted is still unresolved. This is a bit unsettling.

Is educative.io serious about the discussion forum ?

1 Like

Hi Avik,
Sincere apologies for the late reply.

In the base case, there was a typo. It should explicitly return 0. I’ve updated that part.

As for how this is printed after the base case is hit:
1
2
3
4
5

The important thing to note is that there are 2 print statements in the function. The one in line 2 is printed when the function is called. Then it goes deeper into its recursive calls and executes line 2 each time. This gives the pattern of:
5
4
3
2
1
0

After the base case is hit, we keep returning to the previous function (the one which called the current recursive call) and the print statement in line 7 is executed. Since we’re moving back up towards the intital call (rec_count(5)), it goes:
1
2
3
4
5

Hope this makes it clear. Let me know if you need further elaboration.

3 Likes

Hi, I tried a slightly changed version of the code, in fact just one line, and can’t understand why the output comes out to be different. My code is:
def rec_count1(x):
print(x)
if (x==0):
return 0
x=x-1
rec_count1(x)
print(x)
rec_count1(5)

Now, the problem is that there are two 0 in the output, as given below:
5
4
3
2
1
0
0
1
2
3
4
Can somebody explain?

I’m still not understanding how it still adds +1 from 0 when the base case is reached. Once the if statement is fulfilled and it returns 0 shouldn’t it just print 0 again? How is it adding 1 up till 5?

2 Likes

Hello
Can you post your eloborate explanation. I am banging my head to understand this
https://pythontutor.com/visualize.html#mode=display
I used this and still not clear

because in your code, when you reach result 0, your “x” in the recursive call is 0. then when it starts to print(x) ( the second print(x)), it starts from print(0). In contrast, in the original code, “number”=1 when it returns 0, then print(1) will give 1.