Write a recursive function total(nums) that returns the sum of a list: the first item plus the total of the rest, with 0 for an empty list.
What to build
A recursive function over a list.
Requirements
- Write
total(nums). - Return 0 for an empty list.
Input
The first line has n (0 to 500). The second line has n whole numbers (it is empty when n is 0).
Output
The sum.
Constraints
n is from 0 to 500.
Example
Input:
3
4 7 1
Output:
12
Why it works
Each call handles one item and hands the rest on, so the list gets shorter until the base case is reached.
Examples
Example 1 · Input
3 4 7 1
Expected output
12
Example 2 · Input
0
Expected output
0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Base case: an empty list has total 0.
Hint 2
Otherwise: nums[0] + total(nums[1:]).
Solution
Show one correct solution (try it yourself first)
def total(nums):
if not nums:
return 0
return nums[0] + total(nums[1:])
n = int(input())
nums = [int(x) for x in input().split()]
print(total(nums))