medium +20 pts

Basic Calculator

Implement a function that evaluates a simple arithmetic expression with +, -, *, / and parentheses.

Write a function `basic_calculator(expression: str) -> float` that evaluates a simple arithmetic expression consisting of non-negative integers and the operators `+`, `-`, `*`, `/` (floating-point division). The expression may also contain parentheses `(` and `)`. The usual operator precedence applies: `*` and `/` bind stronger than `+` and `-`. All operators are left-associative. Parentheses override precedence. Division by zero must raise a `ZeroDivisionError` (Python's default). The input string is guaranteed to be a valid expression with no spaces, and will contain at least one integer. The result may be fractional and should be returned as a float (e.g., `1/2` -> `0.5`). You may not use `eval()` or `exec()`.

Constraints

Expression length: 1 to 200 characters. Expression contains only non-negative integers and characters `+ - * / ( )`. No spaces. Numbers may have multiple digits. Python's float division is used.

Example

>>> basic_calculator('1+2')
3.0
>>> basic_calculator('2+3*4')
14.0
>>> basic_calculator('(2+3)*4')
20.0
>>> basic_calculator('10/4')
2.5
20 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Process the expression with a stack for numbers and operators, respecting precedence.
Handle parentheses by treating them as subproblems, either via recursion or a stack that restores when encountering a closing parenthesis.
After the full expression is processed, apply all remaining operations in the correct order.
Remember multiplication and division have higher precedence than addition and subtraction.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.