Evaluate a Ternary-Chained Arithmetic Expression
Stacks & QueuesAuto-graded · 17 test casesLast updated
Tests expression evaluation using a monotonic/operator-precedence stack to correctly parse and compute a string containing +, -, *, /, parentheses, and nested ternary operators.
Evaluate a Ternary-Chained Arithmetic Expression
You are given a string expr representing an arithmetic expression that may also contain ternary conditionals. Your task is to evaluate it and return the integer result.
Expression grammar
The expression is built from the following rules (listed in order of increasing precedence):
-
Ternary:
condition ? true_branch : false_branch- The condition is any sub-expression. If it evaluates to a non-zero integer it is truthy;
0is falsy. - Ternary associates right-to-left:
a ? b : c ? d : emeansa ? b : (c ? d : e).
- The condition is any sub-expression. If it evaluates to a non-zero integer it is truthy;
-
Addition / Subtraction:
+,-(left-to-right, equal precedence) -
Multiplication / Integer Division:
*,/(left-to-right, equal precedence, higher precedence than+/-)- Division is truncated toward zero (Python's
int(a / b), nota // b).
- Division is truncated toward zero (Python's
-
Unary minus:
-expr(highest precedence among operators) -
Parentheses:
(expr)override any precedence. -
Atoms: non-negative integer literals (no leading zeros except the literal
0itself).
Parsing specifics
- Tokens are: integer literals,
(,),+,-(binary or unary),*,/,?,:. - Whitespace may appear anywhere between tokens and must be ignored.
- Integer literals fit in a 32-bit signed integer before evaluation; intermediate and final results fit in a 64-bit signed integer.
- Ternary branches: the
:of a ternary is always the one matching the nearest unmatched?(right-to-left association is naturally handled by the grammar). - Ternary has lower precedence than all arithmetic, so
1+2 ? 3*4 : 5-6means(1+2) ? (3*4) : (5-6)→12.
Your task
Implement evaluate_ternary_expr(expr: str) -> int that returns the integer value of the expression.
Constraints
1 ≤ len(expr) ≤ 2000- The expression is always syntactically valid.
- Integer literals are in the range
[-2^31, 2^31 - 1](after applying any unary minus). - Intermediate and final values fit in a 64-bit signed integer.
- Ternary operators may be nested up to depth 50.
- Parentheses may be nested up to depth 50.
- Division by zero will not appear in any test case.
- There is no exponentiation or modulo operator.
Examples
Example 1
Input: evaluate_ternary_expr('1 + 2 * 3')
Output: 7
Example 2
Input: evaluate_ternary_expr('1 ? 10 + 5 : 20 - 3')
Output: 15
Example 3
Input: evaluate_ternary_expr('0 ? 99 : 1 ? 42 : 7')
Output: 42
Hints
Hint 1
Tokenize first: walk the string once to emit a clean list of tokens (integers, operators, parens). Then write a recursive-descent parser with one function per precedence level — ternary at the bottom, then additive, then multiplicative, then unary, then primary (atoms and parenthesised groups). This completely avoids manual stack juggling for precedence.
Hint 2
Ternary right-associativity falls out naturally from recursive descent: after you parse the condition and consume '?', parse the true-branch by calling your ternary-level function recursively, then expect ':', then parse the false-branch the same way. Because the recursive call consumes the entire remaining ternary chain, right-association is free.
Hint 3
Integer division truncated toward zero is NOT the same as Python's '//' for negative operands (e.g. -7 / 2 should be -3, but -7 // 2 is -4). Use int(a / b) or the sign-aware formula: -((-a) // b) when signs differ.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Strategy: Recursive-Descent Parser
The cleanest solution for this grammar is a recursive-descent parser with one parsing function per precedence level. This entirely avoids the need to manage a manual operator-precedence stack or a shunting-yard algorithm, making correctness much easier to reason about.
Step 1 – Tokenise
Walk the string once. Emit integers (as Python int) and single-character operator/punctuation tokens. Strip all whitespace.
Step 2 – Recursive descent, one level per precedence tier
parse_ternary (lowest precedence, right-associative)
└─ parse_additive (+, − left-to-right)
└─ parse_multiplicative (*, / left-to-right)
└─ parse_unary (unary −, right-associative)
└─ parse_primary (integer literal, or '(' parse_ternary ')')
Ternary right-associativity falls out for free: after consuming ?, we call parse_ternary() for the true branch; that call itself may consume another ternary chain before returning. Same for the false branch.
Left-to-right arithmetic is handled by a while peek() in operators loop that keeps accumulating left.
Step 3 – Truncation toward zero
Python's // floors (e.g. -7 // 2 == -4), but the problem requires truncation toward zero (-7 / 2 == -3). Use int(a / b) which calls C's trunc via Python's float conversion. For values within 64-bit range this is exact.
Correctness
- Every grammar production is directly encoded as one function.
- The token cursor advances monotonically; no token is ever consumed twice or skipped.
- Ternary short-circuit evaluation: we still parse both branches (to advance the cursor) but only return the relevant one — the problem is deterministic so no side effects exist.
Complexity
- Time: O(n) tokenisation + O(n) parsing = O(n) overall (each token is visited a constant number of times).
- Space: O(n) for the token list + O(d) call stack where d ≤ nesting depth ≤ 50 = O(n).
Reference solution
from typing import List
def evaluate_ternary_expr(expr: str) -> int:
tokens: List = []
i, n = 0, len(expr)
while i < n:
c = expr[i]
if c.isspace():
i += 1
elif c.isdigit():
j = i
while j < n and expr[j].isdigit():
j += 1
tokens.append(int(expr[i:j]))
i = j
elif c in '+-*/?(: )':
tokens.append(c)
i += 1
else:
raise ValueError(f"Unexpected character: {c!r}")
pos = 0
def peek():
return tokens[pos] if pos < len(tokens) else None
def consume(expected=None):
nonlocal pos
tok = tokens[pos]
if expected is not None and tok != expected:
raise ValueError(f"Expected {expected!r}, got {tok!r}")
pos += 1
return tok
def parse_ternary():
cond = parse_additive()
if peek() == '?':
consume('?')
true_val = parse_ternary()
consume(':')
false_val = parse_ternary()
return true_val if cond != 0 else false_val
return cond
def parse_additive():
left = parse_multiplicative()
while peek() in ('+', '-'):
op = consume()
right = parse_multiplicative()
left = left + right if op == '+' else left - right
return left
def parse_multiplicative():
left = parse_unary()
while peek() in ('*', '/'):
op = consume()
right = parse_unary()
left = left * right if op == '*' else int(left / right)
return left
def parse_unary():
if peek() == '-':
consume('-')
return -parse_unary()
return parse_primary()
def parse_primary():
tok = peek()
if tok == '(':
consume('(')
val = parse_ternary()
consume(')')
return val
if isinstance(tok, int):
return consume()
raise ValueError(f"Unexpected token in primary: {tok!r}")
return parse_ternary()