FunctionRacerProblemsRace

Nested Expression Value

EasyRecursionPython, JavaScript, TypeScript

expr is an arithmetic expression written as nested lists. It is either an integer, or a list of exactly three items [op, left, right] where op is one of the strings "+", "-" and "*", and left and right are themselves expressions of the same form. Return the value of expr as an integer.

The shape is recursive, so the evaluator is too: a plain integer is its own value; otherwise evaluate both sides and combine them with the operator.

For example, ["+", 2, ["*", 3, 4]] means 2 + (3 * 4) and gives 14, and ["-", 10, ["-", 4, 1]] means 10 - (4 - 1) and gives 7.

Example 1

expr ["+",2,["*",3,4]]
returns 14

The right side ["*", 3, 4] is 12, and 2 + 12 = 14.

Example 2

expr ["-",10,["-",4,1]]
returns 7

The right side ["-", 4, 1] is 3, and 10 - 3 = 7; the order of the operands matters.

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