Google questions

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:

  • add returns left + right, sub returns left - right and mul returns left * right.
  • div returns the integer quotient of left by right, truncated toward zero: div(7, 2) is 3 and div(sub(1, 9), 3) is -2.
  • pow returns left raised to the power right; any number to the power 0 is 1.
  • A number alone is its own value.
  1. Example 1
    expression
    "add(2, mul(3, pow(4, 5)))"
    Output
    3074

    Why: pow(4, 5) is 1024, mul(3, 1024) is 3072, and add(2, 3072) is 3074.

  2. Example 2
    expression
    "add(1, sub(1, 0))"
    Output
    2

    Why: sub(1, 0) is 1, and add(1, 1) is 2.

Constraints

  • 1 <= len(expression) <= 10^4
  • Calls in expression are nested at most 100 levels deep
  • 0 <= literal <= 10^9 for every number in expression
  • The divisor of every div in expression is not 0
  • The exponent of every pow in expression is not negative
  • Every intermediate value in expression fits 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.
Import a question