hard +45 pts

Basic Calculator III

Evaluate arithmetic expressions with +, -, *, / and parentheses.

Write a function `evaluate(expr: str) -> int` that evaluates a mathematical expression string and returns the integer result. The expression may contain: - Non-negative integers (0-9, no decimal points) - Operators: `+`, `-`, `*`, `/` (all binary) - Parentheses `(` and `)` - Spaces Rules: 1. Evaluate with standard operator precedence: `*` and `/` have higher precedence than `+` and `-`. 2. Evaluate left-to-right for operators with same precedence. 3. Parentheses override precedence. 4. Division is integer division truncating toward zero (e.g., 7/2 = 3, -7/2 = -3). 5. No division by zero in test cases. 6. Input is guaranteed to be a valid expression. 7. Operators `-` and `+` may also appear as unary signs? No, only binary. However, a number may be immediately preceded by a unary minus inside parentheses? No, only binary. 8. Negative numbers do not appear as inputs. 9. The expression length is at most 10000 characters. Constraints: - 1 <= len(expr) <= 10000 - expr contains only digits, operators, parentheses, and spaces. - The expression is always valid. - Integer values and results fit in a signed 64-bit integer.

Constraints

Expression length up to 10000. All intermediate values fit in 64-bit signed integers. Operations are integer division truncating toward zero. Input always valid.

Example

```python
>>> evaluate("1 + 1")
2
>>> evaluate(" 6-4 / 2 ")
4
>>> evaluate("2*(5+5*2)/3+(6/2+8)")
21
>>> evaluate("(2+6* 3+5- (3*14/7+2)*5)+3")
-12
```
45 points ~40 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a recursive descent parser with two levels: one for addition/subtraction, one for multiplication/division.
Handle parentheses by making a recursive call when you see '('.
Keep an index pointer that is shared across parser functions to avoid slicing the string repeatedly.
Skip spaces while parsing. After reading a number, continue parsing the current expression level.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.