Nova has a list of glow readings from three stars. Rocket wants the total, and he wants to use recursion.
"But a list is not a number," he says. "How do I make a list smaller?"
Raven covers the first number with her finger. "What do you notice about what is left?"
"It is a shorter list!" Rocket says.
Nova hums. "Here is a hint. The total is the first number plus the total of the rest."
A slice takes part of a list. nums[1:] means every item from spot 1 to the end. It skips the first item.
nums = [3, 5, 2] print(nums[0]) print(nums[1:]) print(nums[1:][1:]) print([2][1:])
Output: 3 [5, 2] [2] []
A list with one item, sliced, becomes the empty list []. The empty list is our base case. It adds up to 0.
def total(nums):
if nums == []:
return 0
return nums[0] + total(nums[1:])
print(total([3, 5, 2])) Output: 10
def count_items(nums):
if nums == []:
return 0
return 1 + count_items(nums[1:])
print(count_items([4, 9, 2]))
print([7, 8, 9][1:]) | Statement | True or false? |
|---|---|
| nums[1:] is always one item shorter than nums, if nums is not empty. | ? |
| count_items([9]) returns 9. | ? |
| total([9]) returns 9. | ? |
| Both functions stop at the empty list. | ? |
Brilliant! You added a list with recursion. Tomorrow we count with recursion and fix a sneaky base case bug.