Challenge 2
- Algorithms course
- Beginner
- Lesson 78/80
- 4 min
Use linear search to find a target.
Challenge 2: Recursion
In this challenge you will write a recursive function. Sum the elements of an array recursively.
Array: [1, 2, 3, 4, 5]. Sum: 15. Base case: return 0 for an empty array.
Practice Recursive array sum
Write recursive_sum(arr). If empty return 0, else arr[0] + recursive_sum(arr[1:]). Print 15 with print(recursive_sum([1,2,3,4,5])).
Starter code
def recursive_sum(arr):
# Recursive sumSample solution
def recursive_sum(arr):
# Recursive sum
if len(arr) == 0:
return 0
return arr[0] + recursive_sum(arr[1:])
print(recursive_sum([1, 2, 3, 4, 5]))Expected output
15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Base case
If the array is empty, return ____.
If the array is empty, return 0.
Explanation: 0 is right.
2 Challenge 2: match the terms
| Term | Meaning |
|---|---|
recursive |
Self-call |
base |
Empty array |
sum |
0 base |
arr[0] |
First element |