Validate-As-You-Go Calculator with Positive Integer Results
Trees & GraphsModel answerLast updated
Evaluate a split-based arithmetic expression, returning false the moment any literal or intermediate value is non-positive or non-integer.
You are given a string containing an arithmetic expression. Its literals are integers written in decimal, and its binary operators are +, -, * and /. The expression may contain parentheses and spaces.
Compute the value of the expression under a strict rule: every literal, every operand and every intermediate result must be a strictly positive integer. If any part of the expression breaks this rule, the answer for the whole expression is Boolean false. A later operation can never "repair" an invalid part.
Provided helper
You may assume a function split(s) already exists. It breaks an expression at its outermost operation and returns one of:
- a one-element tuple holding a literal, e.g.
split("5") -> ("5",) - a three-element tuple
(left, operator, right), e.g.split("(10 / 2) / 5") -> ("(10 / 2)", "/", "5")
The operand strings in the tuple may need further evaluation. You do not need to write a parser. Behaviour of split on malformed input is not defined, so you may assume inputs are well formed.
Rules
- A literal is valid only if, after trimming whitespace and enclosing parentheses, it is a positive integer. Zero is invalid.
+and*use exact integer arithmetic.a - bis invalid when the result is zero or negative.a / bis invalid whenbis zero or whenais not exactly divisible byb. Never round or truncate.- Return the final positive integer, or
falseif anything along the way is invalid.
Examples
"(3 + (3 * 5)) / 2" -> 9
"((3 - 5) + 12) / 2" -> false (3 - 5 is negative)
"8 / 12" -> false (not an exact division)
"3 - 3" -> false (zero is not positive)
What to deliver
Write evaluate(expression) using split. Explain your approach, justify its correctness, state its time and space complexity, and describe the edge cases you handle. Be ready to discuss what changes if nesting can be very deep.
Hints
Hint 1
Treat the output of `split` as a binary tree: a one-element tuple is a leaf and a three-element tuple is an internal node. What traversal order lets you compute a node only after its children?
Hint 2
Decide on an invariant for the return value: it is always either a strictly positive integer or `false`. Check for failure after each child returns, before doing any arithmetic.
Hint 3
Only subtraction and division can produce an invalid result from valid operands. Subtraction needs left > right; division needs a nonzero divisor and a zero remainder. In Python, remember `False == 0`, so test failure with `is False`.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The helper split exposes the expression tree one level at a time, so the task is a post-order recursive evaluation with a single invariant:
evaluatereturns either a strictly positive integer orFalse.
For each node:
- Leaf (one-element tuple): trim whitespace and any enclosing parentheses, then check that the remaining text is a string of ASCII digits whose value is greater than zero. Return the integer, or
False. - Internal node (three-element tuple): evaluate the left operand; if it is
False, returnFalseimmediately. Do the same for the right operand. - Apply the operator:
+and*: positive operands always give a positive result.-: valid only ifleft > right./: valid only ifright != 0andleft % right == 0; the result isleft // right.
An invalid value propagates to the root, so later operations cannot fix it.
Why it is correct
Use structural induction on the tree.
- Base case: a leaf is valid exactly when its trimmed text is a positive integer, and the function returns that integer or
False. - Inductive step: assume each child returns its correct positive value or
False. If either child isFalse, the whole expression is invalid by the rules, and we returnFalse. Otherwise both operands are positive integers, and the operator checks accept exactly the cases that give a positive integer: sums and products always do,a - b > 0iffa > b, anda / bis an integer iffbdividesa(and is then positive).
Because arithmetic is exact, 8 / 12 is rejected rather than truncated to 0. Short-circuiting on a failed left operand does not change the answer; it only saves work.
Code
def evaluate(expression):
parts = split(expression)
if len(parts) == 1:
return _parse_literal(parts[0])
left_expr, op, right_expr = parts
left = evaluate(left_expr)
if left is False:
return False
right = evaluate(right_expr)
if right is False:
return False
if op == "+":
return left + right
if op == "*":
return left * right
if op == "-":
return left - right if left > right else False
if op == "/":
if right == 0 or left % right != 0:
return False
return left // right
return False # unknown operator
def _parse_literal(text):
s = text.strip()
while len(s) >= 2 and s[0] == "(" and s[-1] == ")":
s = s[1:-1].strip()
if not s or not (s.isascii() and s.isdigit()):
return False
value = int(s)
return value if value > 0 else False
Trace of "(3 + (3 * 5)) / 2": the top split is ("(3 + (3 * 5))", "/", "2"). The left side evaluates to 3 + 15 = 18, the right side is 2, and 18 % 2 == 0, so the result is 9.
For "((3 - 5) + 12) / 2", the inner 3 - 5 fails left > right, False propagates upward, and the answer is False.
Complexity
Let n be the number of nodes, L the string length and d the tree depth.
- Time: O(1) arithmetic per node plus literal trimming proportional to literal length, with O(n) calls to
split. Ifsplitscans its input linearly, total cost is O(L * d): about O(L) for balanced trees and O(L^2) for deeply nested ones. Big-integer multiplication can add cost for huge values, usually ignored. - Space: O(d) for the recursion stack plus the substrings
splitcreates.
Trade-offs and pitfalls
- The bool/int trap. In Python,
False == 0andFalse + 3 == 3. Never letFalsereach arithmetic, and test withis False, notnot leftor== 0. Since valid values are always positive,0is never a legitimate result, but the explicit check keeps intent clear. - Exact division. Use
%to test divisibility. Floats or//alone would silently accept8 / 12as0. - Literal validation.
str.isdigitaccepts characters like"²", so also requireisascii(). Reject signs, decimals and empty strings. Leading zeros like"007"are fine and give7. - Deep nesting. Recursion may hit Python's default limit of about 1000 frames. Either raise the limit or convert to an explicit stack with a post-order traversal.
- Zero is never valid, whether it appears as a literal or comes from a subtraction.
Edge cases
| Input | Result | Reason |
|---|---|---|
"5" | 5 | single literal |
" ( 5 ) " | 5 | whitespace and parentheses stripped |
"0 + 3" | false | zero literal |
"3 - 3" | false | zero intermediate |
"(3 - 5) + 12" | false | negative intermediate cannot be repaired |
"8 / 12" | false | inexact division |
"12 / 4" | 3 | exact division |
"2.5", "-4", "abc" | false | not a positive integer literal |
Malformed input depends on split, which the problem leaves unspecified. State that assumption explicitly rather than guessing.
Likely follow-ups
- Implement
splityourself: scan tracking parenthesis depth to find the outermost operator, respecting precedence and left associativity. - Replace recursion with a stack-based evaluator (shunting-yard) that applies the same positivity checks.
- Return a reason for failure instead of
False, for example an error describing which subexpression broke the rule.