CodeBlanks Logo Icon CodeBlanks

Challenge 2

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

solution.py
def recursive_sum(arr):
    # Recursive sum

Sample solution

solution.py
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

Question
If the array is empty, return ____.
Answer
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

All lessons in Beginner