Do I finally understand Recursion or am I horribly Wrong?

Question:

Firstly I am aware that recursion questions have been asked as I’ve looked through many of them as well as YouTube and other sources. My main question is have I understood how it works enough or am I horribly wrong?

Below is the code along with how I personally broke it down:

def rec(a):  # will end when the condition is no longer greater than 0
    if a > 0:
        r = a + rec(a - 1)  # decrements -1 each time a recurse happens
        print(r)
    else:
        r = 0
    return r


print("nnRecursion Results are")
rec(3)

break down:

1st call: # not a recurse, so the -1 doesn’t apply
rec(a) = rec(3)
3 > 0, so r = 3 + rec(3 – 1) which equals "6" as the "- 1" is ignored

2nd call: # 1st recurse so subtract 1
rec(a) = rec(2)
2 > 0, so r = 2 + rec(2 – 1) which equals "3"

3rd call: # 2nd recurse so subtract 1 again
1 > 0, so r = 1 + rec(1 – 1) which equals "1"

Since the recursion ends if the number is not greater than "0" and "1" is the last number before "0", it means "1" is the final result you’ll get as an output.
The reason "1" displays 1st and "6" displays last is due to the fact "1" is
the base or end point while "6" is where the count down starts from, ending at "1"

Asked By: simmo

||

Answers:

Add more print statements for each step and it should be clear. Your function only knows the answer to rec(0) = 0, so it recurses down until it gets a result, then starts computing the answers to rec(1), etc.:

def rec(a):  # will end when the condition is no longer greater than 0
    print(f'rec({a}) called')
    if a > 0:
        print(f'Compute {a} + rec({a - 1})')
        r = a + rec(a - 1)  # decrements -1 each time a recurse happens
        print(f'{a} + rec({a - 1}) computes to {r}')
    else:
        print(f'termination condition: rec({a}) computes 0')
        r = 0
    print(f'rec({a}) returned {r}')
    return r

print("Recursion results are:")
rec(3)

Output:

Recursion results are:
rec(3) called
Compute 3 + rec(2)
rec(2) called
Compute 2 + rec(1)
rec(1) called
Compute 1 + rec(0)
rec(0) called
termination condition: rec(0) computes 0
rec(0) returned 0
1 + rec(0) computes to 1
rec(1) returned 1
2 + rec(1) computes to 3
rec(2) returned 3
3 + rec(2) computes to 6
rec(3) returned 6
Answered By: Mark Tolonen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.