62. Sum a nested list
Write a function nested_sum(items) that takes a list and returns the total of all the numbers in it. Each item is
either a whole number or another list built the same way, so lists can sit inside lists to any depth: [1, [2, [3]]]
holds 1, 2 and 3.
- Add up the numbers at every depth.
- An empty list, at any depth, adds nothing, so
[]and[[], [[]]]both add up to 0.
A loop alone can't do this, because you don't know how deep the lists go. Each inner list is the same problem again, only smaller.
Example 1
items = [1, [2, 3], [[4]], 5]15Example 2
items = [[1, [2, [3, [4]]]]]10Example 3
items = [[], [[]]]0Constraints
itemsholds whole numbers from -1000 to 1000 and lists, nested at most 20 deep, with at most 100 numbers in all.
Submit also runs 7 more tests you can't see.
Practises Recursion (lesson 20).
- Go through the items one by one.
isinstance(item, list)tells you whether an item is a list or a number. - A number is added to the total. A list's total is the same problem on a smaller list: call
nested_sum(item)and add what it returns. - An empty list never enters the loop, so it returns 0: that's what stops the calls. Adding up only one level (
sum(item)for an inner list) fails on deeper lists.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def nested_sum(items):
"""Add up the numbers in a nested list.
items: list of ints and lists, nested to any depth
Returns: int, the total of every number at every depth
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.