Rocket copies the total function to add a new list. The answer comes out 11, but the numbers only add to 10.
"I checked my adding three times," Rocket says. "I am sure the list is right."
Raven traces the calls on paper. "What do you notice about the very last call?"
Rocket squints. "The empty list returns 1. But an empty list has nothing in it!"
Nova cheers. "Great discovery! Here is a hint. Every wrong base case answer gets added in."
def total(nums):
if nums == []:
return 1
return nums[0] + total(nums[1:])
print(total([3, 5, 2])) Output: 11
The base case is reached once, at the very end. Its value is added into every answer above it. So a base case of 1 makes every total 1 too big.
def total(nums):
if nums == []:
return ____
return nums[0] + total(nums[1:])
print(total([3, 5, 2])) This function counts the readings bigger than 5. It has one base case and two smaller steps.
def count_big(nums):
if nums == []:
return 0
if nums[0] > 5:
return 1 + count_big(nums[1:])
return count_big(nums[1:])
print(count_big([8, 2, 9, 6, 1])) Output: 3
| Statement about count_big | True or false? |
|---|---|
| Every call makes the list one item shorter. | ? |
| count_big([6]) returns 1. | ? |
| The base case returns 1. | ? |
def count_small(nums):
if nums == []:
return 0
if nums[0] < 3:
return 1 + count_small(nums[1:])
return count_small(nums[1:])
print(count_small([1, 5, 2, 2, 8])) | Statement | True or false? |
|---|---|
| count_small has one base case. | ? |
| count_small has two smaller steps. | ? |
| count_small([3]) returns 1. | ? |
| Both smaller steps use nums[1:]. | ? |
Week 4 complete! You can name the base case, spot a missing one and fix a wrong one. Next week we race loops against recursion.