Python Forum
Execution of Another Recursive Function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Execution of Another Recursive Function
#1
Greetings,

I want to make sure that I understand the execution of the following "simple" recursive function that basically takes a number and adds it to every number below it. This function will output the value of 10.


def get_recursive_sum(n):
    if n < 0:
        return -1
    elif n == 0:
        return 0
    else:
        return n + get_recursive_sum(n - 1)

print(get_recursive_sum(4))
I am going to make the following assumption here. Please correct me if I am wrong.

  1. 1. Each recursive call simply returns the value of n to each child recursive call. Basically the variable n will be overwritten by returning the sum of
    n = n + get_recursive_sum(n - 1)
    to each of the child calls until we get to zero. Recursion stops and the last value is returned to the initial caller which is the value of 10.

    2. Starting with the first call n = 4, 4 and subsequent values are added then overwritten by return values. As I stated above
    n = n + get_recursive_sum(n - 1)

Something like:
4 + get_recursive_sum(4 - 1) #returns 7 
                7 + get_recursive_sum(3 - 1) #returns 9
                   9 + get_recursive_sum(2 - 1) #returns 10
                      10 get_recursive_sum(1 - 1) #stops because n = 0
       #return 10 to initial caller.
Did I correctly describe the execution of this function?

Thanks,
Matt
Reply


Messages In This Thread
Execution of Another Recursive Function - by muzikman - Dec-03-2020, 05:07 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  with open context inside of a recursive function billykid999 1 636 May-23-2023, 02:37 AM
Last Post: deanhystad
  Why recursive function consumes more of processing time than loops? M83Linux 9 4,399 May-20-2021, 01:52 PM
Last Post: DeaD_EyE
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,593 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  Don't Understand Recursive Function muzikman 9 3,833 Dec-03-2020, 05:10 PM
Last Post: muzikman
  list call problem in generator function using iteration and recursive calls postta 1 2,001 Oct-24-2020, 09:33 PM
Last Post: bowlofred
  Recursive function returns None, when True is expected akar 0 3,452 Sep-07-2020, 07:58 PM
Last Post: akar
  factorial using recursive function spalisetty06 12 4,225 Aug-25-2020, 03:16 PM
Last Post: spalisetty06
  Recursive Function sridhar 7 2,931 Jul-14-2020, 07:53 PM
Last Post: deanhystad
  Nested Recursive Function not Returning Etotheitau 2 2,360 May-09-2020, 06:09 PM
Last Post: Etotheitau
  Information "creeps up" in recursive function InigoMontoya 2 1,928 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