Deviopath › Python

Evaluate an Arithmetic Expression

Hard · Parsing

Calculators must respect precedence: * and / bind tighter than + and -, operators of the same level go left to right, and parentheses come first. A recursive descent parser mirrors these rules with one function per level:

- expr: a term, then any number of + term or - term - term: a factor, then any number of * factor or / factor - factor: a number, or ( expr )

First split the string into tokens (numbers and symbols, skipping spaces), then parse.

Write evaluate(expr) that returns the integer result. Rules:

- numbers are non-negative integers; there is no unary minus (but results can be negative) - / is integer division that truncates toward zero: 7 / 2 is 3 and (2 - 9) / 2 is -3 (careful: Python // would give -4) - the expression is always valid and never divides by zero - do NOT use eval()

Next: Status Runs with groupby