Dec-03-2020, 05:07 PM
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.
Something like:
Thanks,
Matt
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. 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 aboven = 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