FunctionRacerProblemsRace

Sum Then Product

EasyRecursionPython, JavaScript, TypeScript

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

items [1,[2,3],[4,[5,6]]]
returns 51

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

items [1,2,3]
returns 6

There are no inner lists, so the answer is the plain sum 6.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Recursion problems