Search code examples
pythonrecursiondata-structuresstack

understanding recursion stack sum_integers


I am doing a practice problem on recursion.

Implement sum_integers(n) to calculate the sum of all integers from 1 to 𝑛 using recursion. For example, sum_integers(3) should return 6 ( 1+2+3 ).

I solved the problem without really understanding what I actually did...

def sum_integers(n):
    if n == 0:
        return 0
    else:
        return n + sum_integers(n-1)
    pass

The base case, I understand.

lets say we call sum_integers(3)

sum_integers(3)
  sum_integers(2)
      sum_integers(1)
         sum_integers(0)
            return 0

I don't understand once I return 0 what/how is it going back up the stack.

In my head this is what's happening

  • 0 + sum_integers(1) = 0 + 1
  • 0 + 1 + sum_integers(2) = 0 + 1 + 2
  • 0 + 1 + 2 + sum_integers(3) = 0 + 1 + 2 + 3

I don't know for sure though. I'm just trying to understand it a bit better.


Solution

  • The 0 + 1 + 2 + sum_integers(3) = 0 + 1 + 2 + 3 is not really correct, an easier way to see it could be

    sum_integers(3)             # go down in recursion
    3 + sum_integers(2)         # go down in recursion
    3 + 2 + sum_integers(1)     # go down in recursion
    3 + 2 + 1 + sum_integers(0) # go down in recursion
    3 + 2 + 1 + 0               # stop because 'return 0'
    3 + 2 + 1                   # go back and apply the plus
    3 + 3                       # go back and apply the plus
    6                           # go back and apply the plus