Evaluate a formula
A spreadsheet cell holds a small arithmetic formula, and the recalculation pass turns it into a number.
- Non-negative whole numbers with + - * / between them. No brackets.
- Multiplication and division bind tighter than addition and subtraction.
- Division truncates towards zero: 7/2 is 3.
- Whitespace anywhere is ignored.
- A division by zero makes the whole formula 0.
evaluate_expression(text: string) → int
Where you start
def evaluate_expression(text: str) -> int:
Worked examples
| Call | Result |
|---|---|
evaluate_expression("2+3*4") | 14 |
evaluate_expression("10-2-3") | 5 |
evaluate_expression("7/2") | 3 |
evaluate_expression("2*3+4*5") | 26 |
Hint
Carry a running total plus one pending term. On + or - you bank the pending term; on * or / you fold the new number into it.
Reference solution in Python
def evaluate_expression(text: str) -> int:
clean = ''.join(text.split())
total = 0
term = 0
num = 0
op = '+'
for i in range(len(clean) + 1):
c = clean[i] if i < len(clean) else '#'
if c.isdigit():
num = num * 10 + int(c)
continue
if op == '+':
total += term
term = num
elif op == '-':
total += term
term = -num
elif op == '*':
term = term * num
else:
if num == 0:
return 0
q = abs(term) // num
term = q if term >= 0 else -q
op = c
num = 0
return total + term