Drill

ProblemsPython › text

Evaluate a formula

hardtextPython

A spreadsheet cell holds a small arithmetic formula, and the recalculation pass turns it into a number.

evaluate_expression(text: string) → int

Solve it in the editor →

Where you start

def evaluate_expression(text: str) -> int:
    

Worked examples

CallResult
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

The same problem in another language

More text problems in Python