Function Expression Evaluator
GoogleOnsiteMedium
You are given expression, a string that is either a non-negative integer or a call such as add(2, mul(3, 4)). A call's name is one of add, sub, mul, div and pow, and each of its arguments is itself an expression. Arguments are separated by commas, and a space may appear after a comma.
Implement evaluate(expression: str) -> int that returns the value of expression.
Part 1: Two-argument calls
Every call has exactly two arguments, left and right, separated by a comma. Return the value of expression, where:
addreturnsleft + right,subreturnsleft - rightandmulreturnsleft * right.divreturns the integer quotient ofleftbyright, truncated toward zero:div(7, 2)is3anddiv(sub(1, 9), 3)is-2.powreturnsleftraised to the powerright; any number to the power0is1.- A number alone is its own value.
- Example 1
- expression
"add(2, mul(3, pow(4, 5)))"- Output
3074
Why:
pow(4, 5)is 1024,mul(3, 1024)is 3072, andadd(2, 3072)is 3074. - Example 2
- expression
"add(1, sub(1, 0))"- Output
2
Why:
sub(1, 0)is 1, andadd(1, 1)is 2.
Constraints
1 <= len(expression) <= 10^4- Calls in
expressionare nested at most 100 levels deep 0 <= literal <= 10^9for every number inexpression- The divisor of every
divinexpressionis not 0 - The exponent of every
powinexpressionis not negative - Every intermediate value in
expressionfits in a signed 64-bit integer
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.