Build a Calculator with Variables, Unary Signs and Parentheses
Stacks & QueuesModel answerLast updated
Write a linear-time evaluator for integer expressions with variables, precedence, unary signs, parentheses, truncating division and 64-bit error handling.
Write a function that evaluates an arithmetic expression given as a string, using a dictionary of variable values.
Input
expr: a string made of non-negative integer literals, variable names (letters only), the operators+,-,*,/, parentheses(and), and space characters.variables: a mapping from variable name to integer value.
Output
The value of the expression as a signed 64-bit integer.
Rules
*and/bind tighter than+and-.- Operators of equal precedence are applied left to right, so
8 - 3 - 2is3. - Unary
+and-are allowed anywhere an operand may start, for example-x,2 * -3and--4. - Integer division truncates toward zero, so
-7 / 2gives-3, not-4. - Signal an error for an invalid character, a malformed expression, mismatched parentheses, an unknown variable, division by zero, or a result outside the signed 64-bit range.
- Time must be O(L) and extra space O(L), where L is
len(expr).
Examples
expr | variables | result |
|---|---|---|
"3 + 4 * 2" | {} | 11 |
"(1 + 2) * 3" | {} | 9 |
"2 * -x" | {x: 4} | -8 |
"-7 / 2" | {} | -3 |
"(1 + 2" | {} | error |
Follow-ups
- Add exponentiation
^, which is right-associative. - Add a two-argument function call
max(a, b).
Describe your approach, give the complexity, and write the code.
Hints
Hint 1
Write the grammar down first, one rule per precedence level: sums of products, products of signed operands, and a base case of number, variable or parenthesised group. Each rule becomes a small function.
Hint 2
Tokenize the string in one pass before evaluating. Then evaluate directly while parsing, with no tree. Use a loop at each level to get left associativity, and call the unary rule for the right operand so that `2 * -3` works.
Hint 3
For truncating division, divide the absolute values and fix the sign yourself, because Python's `//` floors. After parsing, check that every token was consumed, which catches a stray `)` and input like `2 3`.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify the contract first
- Signature:
evaluate(expr, variables) -> int, raisingExprError(aValueErrorsubclass) on any failure. - Errors: bad characters, malformed syntax (
"2 +","2 3","()",""), unbalanced parentheses, unknown variables, division by zero, and a result outside[-2^63, 2^63 - 1]. - Overflow policy: Python integers do not overflow, so I check the range after every arithmetic result and raise. Wrapping like C is the alternative. Either is fine if stated. Bare literals are not range-checked on their own, so
-9223372036854775808is accepted because the negated result fits. The final result is always checked. - Division: truncate toward zero. Divide absolute values, then restore the sign.
Approach: recursive descent over a precedence grammar
Put precedence into the grammar. Each rule handles one tier and calls the tighter tier for its operands:
sum := product (('+' | '-') product)*
product := signed (('*' | '/') signed)*
signed := ('+' | '-') signed | atom
atom := NUMBER | NAME | '(' sum ')'
Two phases:
- Tokenize in one left-to-right scan into numbers, names and single-character symbols. Anything else is rejected immediately.
- Parse and evaluate in the same pass. Each rule returns an integer, so no syntax tree is needed.
Why it works
- Precedence:
sumgets its operands fromproduct, so a whole*and/chain is reduced before any+or-uses it. In1 + 2 * 3, the right operand of+is the finished product6. - Associativity: the loops fold as they go, so
8 - 3 - 2is(8 - 3) - 2. - Unary signs:
signedsits belowproduct, so-2 * 3is(-2) * 3. Becauseproductcallssignedfor its right operand,2 * -3and2 * --3work. - Parentheses:
atomrecurses intosumand then requires). A missing)fails there. An extra)or leftover token (2 3) fails the "all tokens consumed" check at the end. - Syntax errors: a token that no rule accepts (an operator at the end,
()) raises atatom.
Complexity
- Time O(L): the tokenizer touches each character once. The parser consumes each token once and never backtracks. Each operation is O(1) on bounded values.
- Space O(L): the token list is O(L), and recursion depth is at most O(L) for input like
((((...))))or-----x.
Python's recursion limit can be a problem for adversarial nesting. Mention either raising the limit or switching to an iterative two-stack evaluator (operands and operators) with the same bounds.
Code
LO, HI = -(1 << 63), (1 << 63) - 1
class ExprError(ValueError):
pass
def _fit(x: int) -> int:
if x < LO or x > HI:
raise ExprError("64-bit overflow")
return x
def _div(a: int, b: int) -> int:
if b == 0:
raise ExprError("division by zero")
q = abs(a) // abs(b)
return q if (a < 0) == (b < 0) else -q
def _tokenize(s: str) -> list:
toks, i, n = [], 0, len(s)
while i < n:
c = s[i]
if c.isspace():
i += 1
elif c in "0123456789":
j = i
while j < n and s[j] in "0123456789":
j += 1
toks.append(("num", int(s[i:j])))
i = j
elif c.isascii() and c.isalpha():
j = i
while j < n and s[j].isascii() and s[j].isalpha():
j += 1
toks.append(("name", s[i:j]))
i = j
elif c in "+-*/()":
toks.append(("sym", c))
i += 1
else:
raise ExprError(f"invalid character {c!r} at {i}")
return toks
class _Evaluator:
def __init__(self, toks, env):
self.t, self.i, self.env = toks, 0, env
def _peek(self):
return self.t[self.i] if self.i < len(self.t) else (None, None)
def _eat(self, symbols):
kind, val = self._peek()
if kind == "sym" and val in symbols:
self.i += 1
return val
return None
def sum(self) -> int:
acc = self.product()
while (op := self._eat("+-")):
rhs = self.product()
acc = _fit(acc + rhs if op == "+" else acc - rhs)
return acc
def product(self) -> int:
acc = self.signed()
while (op := self._eat("*/")):
rhs = self.signed()
acc = _fit(acc * rhs) if op == "*" else _fit(_div(acc, rhs))
return acc
def signed(self) -> int:
op = self._eat("+-")
if op == "-":
return _fit(-self.signed())
if op == "+":
return self.signed()
return self.atom()
def atom(self) -> int:
kind, val = self._peek()
if kind == "num":
self.i += 1
return val
if kind == "name":
self.i += 1
if val not in self.env:
raise ExprError(f"unknown variable {val!r}")
return _fit(self.env[val])
if self._eat("("):
v = self.sum()
if not self._eat(")"):
raise ExprError("missing ')'")
return v
raise ExprError("unexpected end" if kind is None else f"unexpected {val!r}")
def evaluate(expr: str, variables: dict) -> int:
ev = _Evaluator(_tokenize(expr), variables)
out = ev.sum()
if ev.i != len(ev.t):
raise ExprError(f"unexpected token {ev._peek()[1]!r}")
return _fit(out)
Edge cases to test
| Input | Expected |
|---|---|
" 3 + 4 * 2 " | 11 |
"-7 / 2", "7 / -2" | -3 |
"8 - 3 - 2" | 3 |
"2 * -x", x = 4 | -8 |
"((a))" | value of a |
"9223372036854775807 + 1" | overflow error |
"(1 + 2", "1 + 2)" | mismatched parentheses |
"2 3", "2 +", "()", "" | syntax error |
"2 $ 3" | invalid token |
"1 / 0" | division by zero |
Follow-up 1: ^, right-associative
Add a tier between signed and atom:
signed := ('+' | '-') signed | power
power := atom ('^' signed)?
The exponent is parsed through signed, which can reach power again, so 2^3^2 = 2^(3^2) = 512. This also gives -2^2 = -4 and allows 2^-1. Negative exponents have no integer result, so raise an error. Do not compute huge powers blindly: handle bases 0, 1 and -1 directly, and for any other base raise if the exponent exceeds 63. Otherwise use repeated multiplication with _fit.
Follow-up 2: max(a, b)
Add a , symbol to the tokenizer. In atom, when a name token is followed by (, treat it as a call. Check that the name is max, parse sum, require ,, parse another sum, require ), and return the larger value. Each argument is a full expression, so nesting such as max(1, max(2, 3) * 2) works. A bare name without ( is still a variable lookup. Reject wrong argument counts as syntax errors.
Common mistakes
- Using
//for division, which floors for negatives. - Parsing unary minus at the same level as binary minus, which breaks
2 * -3. - Forgetting the "all tokens consumed" check, so
1 + 2)or2 3is silently accepted. - Making
^left-associative by looping instead of recursing. - Checking overflow only at the end, which hides intermediate errors in languages with wrapping integers.