Evaluate Prize-Pool Formulas with Strictly Positive Whole Steps
Stacks & QueuesModel answerLast updated
Parse and evaluate an infix arithmetic string, rejecting it with False if any intermediate result is zero, negative, or a non-integer quotient.
A prize-pool calculator accepts formulas written as plain arithmetic text. A formula contains positive integer literals, the operators +, -, *, /, and parentheses. Precedence is the usual one: * and / bind tighter than + and -, and operators of equal precedence group left to right.
The formula describes splitting a pool into whole shares, so every value produced during evaluation must be a strictly positive integer. That covers each literal and each intermediate result, not just the final answer. If any step yields zero, a negative number, or a fraction, the whole formula is rejected, even if later steps would have "repaired" the value.
Implement:
def evaluate_share_formula(expression: str) -> int | bool:
...
Return the integer result if all steps are valid, otherwise return False.
Rules
- A literal is a run of digits. The literal
0is invalid. - Subtraction is invalid when the result would be zero or negative.
- Division is invalid if the divisor is zero or if the division is not exact. No rounding or truncation is allowed.
- Addition and multiplication of positive integers are always valid.
- Whitespace between tokens is ignored.
Examples
evaluate_share_formula("((9 * 4) / 6) + 10") # 36 -> 6 -> 16, returns 16
evaluate_share_formula("(20 - 6) / 2") # 14 -> 7, returns 7
evaluate_share_formula("(5 - 9) + 100") # 5-9 = -4 is invalid, returns False
evaluate_share_formula("15 / 4") # not exact, returns False
In the third example -4 + 100 would be 96, but the negative intermediate already invalidates the formula.
Constraints
- Input is always well-formed: digits,
+ - * /, balanced parentheses, optional spaces. There is no unary minus and no leading zeros. - Length is at most 500 characters and nesting depth at most 50.
- Write your own parser. Do not use
evalor a parsing library.
Explain your approach, state its complexity, and provide code.
Hints
Hint 1
Write the grammar down first: an expression is terms joined by + or -, a term is factors joined by * or /, and a factor is a number or a parenthesized expression. Each level maps to one function.
Hint 2
Evaluate while parsing instead of building a tree. Validate each value the moment it is created: after reading a literal and after every binary operation.
Hint 3
Use an exception to abort on the first invalid step so it unwinds through nested parentheses automatically, and catch it once at the top level to return False. Check division with the integer remainder, not floats.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a calculator problem with one extra rule: a value must be a positive integer at every step. The cleanest solution is a recursive-descent parser that evaluates as it parses and validates each value as soon as it is produced.
Grammar
expr := term (('+' | '-') term)*
term := factor (('*' | '/') factor)*
factor := NUMBER | '(' expr ')'
Splitting into expr and term gives * and / higher precedence. Using a loop rather than right recursion gives left-to-right grouping, so 8 / 4 / 2 is (8 / 4) / 2 = 1, and 10 - 3 - 2 is (10 - 3) - 2 = 5.
Validation
- Literals: after parsing a number, reject it if it is 0. There is no unary minus, so literals are never negative.
- Subtraction: after computing
a - b, reject if the result is<= 0. The check must be "strictly positive", so25 - 25is invalid. - Division: reject if
b == 0ora % b != 0. Use integer remainder rather than float division, which avoids precision problems. Otherwise computea // b, which is at least 1 because both operands are positive and the division is exact. - Addition and multiplication: always valid for positive integers, though a uniform "result must be positive" check after every operation is harmless and keeps the code simple.
Short-circuiting on failure
Raising a private exception (InvalidShare) at the first violation is the simplest way to make one bad step void the entire formula, however deeply nested. The exception unwinds through all pending parse_* calls, and the top-level function catches it once and returns False. No manual propagation of error flags is needed.
Note that since the input is guaranteed well-formed, we do not need to handle syntax errors beyond defensive assertions.
Code
class InvalidShare(Exception):
pass
def _tokenize(s: str) -> list[str]:
tokens, i, n = [], 0, len(s)
while i < n:
c = s[i]
if c.isspace():
i += 1
elif c in "+-*/()":
tokens.append(c)
i += 1
else: # digit run
j = i
while j < n and s[j].isdigit():
j += 1
tokens.append(s[i:j])
i = j
return tokens
def evaluate_share_formula(expression: str):
tokens = _tokenize(expression)
pos = 0
def peek():
return tokens[pos] if pos < len(tokens) else None
def take():
nonlocal pos
tok = tokens[pos]
pos += 1
return tok
def expr():
v = term()
while peek() in ("+", "-"):
op = take()
r = term()
v = v + r if op == "+" else v - r
if v <= 0:
raise InvalidShare
return v
def term():
v = factor()
while peek() in ("*", "/"):
op = take()
r = factor()
if op == "*":
v *= r
else:
if r == 0 or v % r != 0:
raise InvalidShare
v //= r
return v
def factor():
tok = take()
if tok == "(":
v = expr()
take() # consume ')'
return v
v = int(tok)
if v <= 0:
raise InvalidShare
return v
try:
return expr()
except InvalidShare:
return False
Tracing the examples:
((9 * 4) / 6) + 10: 36, then 6, then 16. Returns16.(20 - 6) / 2: 14, then 7. Returns7.(5 - 9) + 100:5 - 9 = -4raises, soFalse.15 / 4:15 % 4 != 0raises, soFalse.25 - 25: result 0 raises, soFalse.
Complexity
- Time: O(n). Tokenizing is linear and each token is consumed once by the parser.
- Space: O(n) for the token list plus O(d) recursion depth, where d is the nesting depth (at most 50, far below Python's default recursion limit).
Intermediate values can grow large with repeated multiplication, but Python integers are arbitrary precision, and with at most 500 characters this is not a concern.
Trade-offs and alternatives
- Two stacks (shunting-yard style): also O(n) and avoids recursion, but the validation hook is slightly more awkward since you must check at each reduction. Recursive descent is easier to read and extend.
- Building an AST first: cleaner separation, but unnecessary here since validation can happen during evaluation.
- Returning a sentinel vs. raising: passing
Noneup through every level works but requires a check after every sub-call; exceptions remove that boilerplate.
Common mistakes
- Using
/orint(a / b)for division. Floats can misjudge large values, and truncation silently accepts inexact quotients. - Checking only the final result, so formulas like
(5 - 9) + 100wrongly return96. - Treating zero as valid by checking
< 0instead of<= 0. - Forgetting the zero-divisor check. Since every value is positive, a zero divisor can only come from a literal
0, which the literal check already rejects, but an explicit guard is cheap and safe. - Getting associativity wrong by recursing on the right for
-and/, which makes10 - 3 - 2evaluate as10 - (3 - 2). - Not handling multi-digit literals or whitespace in the tokenizer.
Edge cases
- A lone literal like
"7"returns7; a lone"0"returnsFalse. - Redundant parentheses such as
((((5))))return5. - A bad step inside a parenthesized sub-expression still invalidates the whole formula, even if the parent would otherwise combine it into something positive.