Python Forum
Don't Understand Recursive Function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Don't Understand Recursive Function
#1
Greetings,

I have a recursive function that I ran through the debugger in PyCharm and I am having a difficult time making sense of some of it. Here is the function in question:

def rec_count(number):
    print(number)
    # Base case
    if number == 0:
        return 0
    rec_count(number - 1)  
    print(number)  #After recursion meets base case it then moves on to this print statement. 
                   #When I step into this print statement, it is printing out the numbers in reverse.
                   #What I don't understand is, how can a print statement loop through this number variable?
rec_count(5)
Read the comments to understand my problem. The function prints out the following.

Output:
5 4 3 2 1 0 1 2 3 4 5
When it hits the last print statement, how is it looping through the number variable? It is not a loop but it is acting like one.
Can someone help me understand why this is happening?

Thank You,
Matt
Reply
#2
This is the basic structure of your function:
Output:
rec_count(5) print 5 rec_count(4) print 5
If we expand all calls like that, we get:
Output:
rec_count(5) print 5 rec_count(4) print 4 rec_count(3) print 3 rec_count(2) print 2 rec_count(1) print 1 rec_count(0) print 0 return 0 print 0 -- not called because the return ends this call print 1 print 2 print 3 print 4 print 5
Hope that helps.
Reply
#3
The print statement only prints one number. What is happening is that when you reach the base case, you have 6 instances of rec_count() running. Five are waiting for their call to rec_count() to complete. As each one completes, it moves on with the rest of the program.

As each function finishes, it prints the number. Because of how you have it written, they finish in reverse order, so the numbers are printed in reverse order.

It's not a traditional loop, but recursion is certainly a form of looping. (With different abilities and limitations)
Reply
#4
Your recursive function is doing this:
def rec_count0():
    return 0

def rec_count1():
    print(1)
    rec_count0()  
    print(1)

def rec_count2():
    print(2)
    rec_count1()  
    print(2)

def rec_count3():
    print(3)
    rec_count2()  
    print(3)

def rec_count4():
    print(4)
    rec_count3()  
    print(4)

def rec_count5():
    print(5)
    rec_count4()  
    print(5)

rec_count5()
If you put a break on "return 0" in rec_count0() the call stack would look something like this:
rec_count5
rec_count4
rec_count3
rec_count2
rec_count1
rec_count0

These are all partially completed functions waiting for a function they called to complete. If you set a breakpoint on "return 0" in your rec_count() function your call stack would look similar.
rec_count
rec_count
rec_count
rec_count
rec_count
rec_count

Again these are all partially completed functions that are waiting for a function they called to complete.
Reply
#5
I am going to have to study your examples. I also have another function I need to post that is driving me nuts. I am new to Python and recursion is a new concept to me because I have never used it. Python can also be used as a procedural language, this is probably why recursion works well. However, I am coming from an OOP background and some of the syntax in Python seems a little counterintuitive. I like strictly type languages because you always know what you're dealing with.

Thank you for your help. I sort of understand it now based on both explanations. Basically, each call is a separate instance, which waits until the child calls are finished for each iteration? Then, base case is met and the child functions return and print out their value, which ultimately closes each call before that, ending with the first call? All functions are still running until the traverse in reverse because the parent is waiting for the child to finish; and finally finish with
rec_count(5):
which is the last to be printed.

Oh. Almost forgot. Is the call stack in the debugger the best way to understand the logic behind recursion? I am using PyCharm.

Thank you so much.
Reply
#6
Your visualization really helped me a lot; especially with the nested calls. Thank you.

(Dec-02-2020, 06:03 PM)stranac Wrote: This is the basic structure of your function:
Output:
rec_count(5) print 5 rec_count(4) print 5
If we expand all calls like that, we get:
Output:
rec_count(5) print 5 rec_count(4) print 4 rec_count(3) print 3 rec_count(2) print 2 rec_count(1) print 1 rec_count(0) print 0 return 0 print 0 -- not called because the return ends this call print 1 print 2 print 3 print 4 print 5
Hope that helps.
Reply
#7
I will let you know when I post the other function. Your help will be greatly appreciated. I cannot move forward learning Python until I have completely understood recursion. Especially, the tricky ones where you add two calls of the function together such as
return func(n) + func(n - 1)
etc...
Reply
#8
I avoid recursion whenever possible. It is slow and there is a limit on how many levels deep you can go. You can be a very accomplished programmer and never use recursion.
Reply
#9
(Dec-03-2020, 04:08 PM)deanhystad Wrote: I avoid recursion whenever possible. It is slow and there is a limit on how many levels deep you can go. You can be a very accomplished programmer and never use recursion.

I know. I have never used it during my entire career. Only in school when I was learning Pascal.
Reply
#10
Could you possibly take a look at the following post and let me know if I am visualizing and explaining this the correct way?

Thanks in advance.
Matt
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  with open context inside of a recursive function billykid999 1 574 May-23-2023, 02:37 AM
Last Post: deanhystad
  Why recursive function consumes more of processing time than loops? M83Linux 9 4,226 May-20-2021, 01:52 PM
Last Post: DeaD_EyE
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,358 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  Execution of Another Recursive Function muzikman 5 3,003 Dec-04-2020, 08:13 PM
Last Post: snippsat
  list call problem in generator function using iteration and recursive calls postta 1 1,902 Oct-24-2020, 09:33 PM
Last Post: bowlofred
  Recursive function returns None, when True is expected akar 0 3,386 Sep-07-2020, 07:58 PM
Last Post: akar
  factorial using recursive function spalisetty06 12 4,054 Aug-25-2020, 03:16 PM
Last Post: spalisetty06
  Recursive Function sridhar 7 2,827 Jul-14-2020, 07:53 PM
Last Post: deanhystad
  Nested Recursive Function not Returning Etotheitau 2 2,256 May-09-2020, 06:09 PM
Last Post: Etotheitau
  Information "creeps up" in recursive function InigoMontoya 2 1,851 Sep-17-2019, 06:25 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020