Sum Then Product
items is a nested list of integers: each element is an integer or another list of the same kind, to any depth. Its value is found by two rules that call each other. The value of the outer list items, and of every list at an odd depth (items has depth 1), is the sum of the values of its elements. The value of a list at an even depth is the product of the values of its elements. An integer's value is itself. An empty list is worth 0 when it is summed and 1 when it is multiplied.
Return the value of items. Two functions that call one another, one for summing levels and one for multiplying levels, are the natural way to write it.
For example, [1, [2, 3], [4, [5, 6]]] gives 1 + (2 * 3) + (4 * (5 + 6)) = 51.
Example 1
Depth 1 sums: 1 + (2 * 3) + (4 * (5 + 6)); the lists [2, 3] and [4, [5, 6]] sit at depth 2 and multiply, and [5, 6] at depth 3 sums again.
Example 2
There are no inner lists, so the answer is the plain sum 6.
Constraints
itemsholds at most 60 integers and at most 30 lists in total- Lists are nested at most 8 levels deep
-10 <= value <= 10for every integer- Every list's value and the final answer lie between -1000000 and 1000000
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Recursion problems
- Teams of a Given SizeEasy
- The Climb FunctionEasy
- Count the BlobsMedium
- Discs After k MovesMedium
- Distinct Arrangements in OrderMedium
- Every Route Through the GardenMedium
- Fair SplitMedium
- Fill In the BracketsMedium