from lexer import tokenize def evaluate(text): """Evaluates with * and / binding tighter than + and -.""" tokens = tokenize(text) # First pass: fold the high-precedence operators. folded = [tokens[0]] index = 1 while index < len(tokens): op, rhs = tokens[index], tokens[index + 1] if op == "*": folded[-1] = folded[-1] * rhs elif op == "/": folded[-1] = folded[-1] // rhs else: folded.append(op) folded.append(rhs) index += 2 # Second pass: left-to-right over what is left. total = folded[0] index = 1 while index < len(folded): op, rhs = folded[index], folded[index + 1] total = total + rhs if op == "+" else total - rhs index += 2 return total