The fleet stacks fuel cells in a triangle. The top row has 1 cell, the next has 2, then 3, then 4.
"How many cells is that?" Rocket asks. "I could count them one by one."
Raven remembers the crew tunnel. "What do you notice if you take away the bottom row of 4?"
"A smaller triangle is left!" says Rocket. "So the total is 4 plus the smaller triangle."
Nova sparkles. "Here is a hint. Let the answers travel back up, like in the tunnel."
def sum_to(n):
if n == 0:
return 0
return n + sum_to(n - 1)
print(sum_to(4)) Output: 10
Questions go down: sum_to(4) asks sum_to(3), which asks sum_to(2), and so on to sum_to(0). Answers come back up.
| Call | Waits for | Returns |
|---|---|---|
| sum_to(0) | nothing (base case) | 0 |
| sum_to(1) | sum_to(0) | 1 + 0 = 1 |
| sum_to(2) | sum_to(1) | 2 + 1 = 3 |
| sum_to(3) | sum_to(2) | 3 + 3 = 6 |
| sum_to(4) | sum_to(3) | 4 + 6 = 10 |
def stack(n):
if n == 0:
return 0
return 2 + stack(n - 1)
print(stack(3))
print(stack(5)) | Statement | True or false? |
|---|---|
| stack(2) waits for stack(1). | ? |
| stack(2) returns 2. | ? |
| The answer for stack(3) is built on the way back up. | ? |
| sum_to(3) returns 6. | ? |
Superb! Return values climb back up the stack, one call at a time. Tomorrow we use this to add up a whole list.