← Back to course
Code Crew G5 / Week 04 / Crew Quest
6/6
Week 04 Β· Base case

Crew Quest

Crew Quest: Pass the pile
// Knowing when to stop
⏱ about 15 min

Crew Quest: Pass the pile

Rocket writes numbers on five paper cards and stacks them.

"Let us be the total function," he says. "Each person takes the top card and passes the rest along."

Raven gets the last card and passes an empty hand. "What do you notice about the person with no cards?"

"They say 0, because there is nothing to add," Rocket says.

Nova glows. "Here is a hint. Then the answers travel back, and each person adds their card."

  1. Every recursion needs a base case and a smaller step.
  2. The base case stops the calls. The smaller step moves closer to it.
  3. With no base case, or one that is skipped, Python shows a RecursionError.
  4. Return values come back up the stack, one call at a time.
  5. total(nums) is nums[0] plus total(nums[1:]). The empty list returns 0.
β—‡ PASS THE PILE
Write a number from 1 to 9 on each of four paper cards. Stack them.
Sit in a line. The first person takes the top card and passes the rest.
Keep passing until someone gets no cards. That person says 0.
Pass answers back. Each person adds their card to the number they hear.
The first person says the total. Check it by adding the cards on paper.
For a grown-up
Two people can play by passing the pile back and forth. Ask your child where the base case happened.
RECAP QUESTION
  • Read the question.
  • Tap your answer.
A recursion keeps going until Python shows a RecursionError. What should you check first?
Bonus recap statementTrue or false?
Every recursion needs a base case.?
The smaller step should move away from the base case.?
A skipped base case can cause a RecursionError.?
The empty list is the base case for total.?
WHY THIS EXERCISEA base case plus a smaller step that reaches it makes recursion safe.
What does sum_to(3) return?
What does total([2, 4]) return?
How many lines does beep(2) print?

Quest complete! Next week we solve the same jobs two ways: with a loop and with recursion.

← Friday