764. Evaluate an arithmetic expression with precedence, parentheses and unary minus
Checking a math answer, a calculator tool for an agent, or a tiny config language all need an expression evaluator that respects operator precedence. Using eval is not allowed.
Write evaluate_expression(expr). expr contains non-negative integers, '+', '-', '*', '/', parentheses and spaces. '*' and '/' bind tighter than '+' and '-', and operators of the same precedence go left to right. '/' is integer division that truncates toward zero. A '-' at the start or right after '(' is a unary minus. The input is always valid and never divides by zero.
def evaluate_expression(expr)Example 1
Input: evaluate_expression('3+2*2')
Output: 7
Example 2
Input: evaluate_expression('(1+(4+5+2)-3)+(6+8)')
Output: 23, and evaluate_expression('-7/2') returns -3
Constraints
- Length up to 10,000 characters.
- Nesting depth up to 200.
- Integers can be large; Python ints do not overflow.
Hint 1
Strip spaces first.
Hint 2
Write the grammar before the code.
Hint 3
Python's // floors; the task wants truncation toward zero.
Common mistakes
- Evaluating strictly left to right and ignoring precedence.
- Making '-' right associative by recursing on the right side.
- Using // directly and getting -4 for -7/2.
- Forgetting unary minus after '('.
Understand the idea
Operator precedence maps neatly to a recursive descent parser: each precedence level is a function that calls the next tighter level for its operands. Parentheses and unary minus live at the tightest level, factor. A stack-based approach (shunting yard, or a running sum with a last term for + - * /) is the common alternative and is worth knowing as a follow-up.