#47 · Recursion and backtracking · Beginner · 40 XP · about 8 min
A nested list holds numbers and other lists, which can hold more lists, to any depth. Write nested_sum(items) that returns the total of every number inside items, however deeply it is buried.
nested_sum([1, [2, 3], [4, [5, [6]]]]) # returns 21 nested_sum([]) # returns 0 nested_sum([[[]], [1.5, [2.5]]]) # returns 4.0
In the first example the numbers are 1, 2, 3, 4, 5 and 6, which add up to 21.
Empty lists add nothing, so nested_sum([]) is 0. The numbers can be integers or floats.
Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.