Run a Tiny Postfix Command Interpreter with Error Codes
Stacks & QueuesModel answerLast updated
Simulate a small stack machine over whitespace-separated tokens, handling arithmetic, DUP, POP and PRINT, and stop at the first error while keeping the output produced so far.
Task
Write an interpreter for a minimal stack-based language over integers. The program arrives as one string of tokens separated by whitespace, and you run it from the first token to the last.
The interpreter keeps two things: a stack of integers and a list of printed values.
Tokens
- Integer literal: an optional
+or-followed by one or more ASCII digits, such as42,-7or+0. Push its value. +,-,*,/: popbfirst, then popa, and push the result ofa op b. For/, the result is the quotient truncated toward zero, so-7 / 2gives-3.DUP: push a copy of the top value.POP: remove the top value and discard it.PRINT: pop the top value and append it to the output list.
Commands are case-sensitive. A lone + or - is an operator, not a number.
Errors
Execution stops at the first error. Everything already appended to the output stays in the result. Possible error codes:
"UNDERFLOW": the operation needs more values than the stack holds. For binary operators, this check comes before the zero-divisor check."ZERODIVISION":/is executed with a divisor of0."INVALID_TOKEN": the token is neither a known command nor a valid integer literal.
Signature
def evaluate_stack_program(program: str) -> tuple[list[int], str | None]:
"""Return (output_list, error_code); error_code is None on success."""
Examples
evaluate_stack_program("10 4 - PRINT") # ([6], None)
evaluate_stack_program("7 PRINT 5 0 / PRINT") # ([7], "ZERODIVISION")
evaluate_stack_program("3 DUP * PRINT POP") # ([9], "UNDERFLOW")
Constraints
0 <= len(program) <= 10^4- Tokens are separated by one or more whitespace characters. An empty or whitespace-only program returns
([], None). - All values fit in a signed 64-bit integer.
- Values left on the stack when the program ends are not an error.
What to explain
Describe your approach, how you classify tokens, how you handle the division rule and error order, the time and space complexity, and the edge cases you would test.
Hints
Hint 1
Split on whitespace and process tokens in order. Decide what each token is before touching the stack: first check the fixed command names, then check whether it is a well-formed literal, otherwise report an invalid token.
Hint 2
For binary operators, the first value popped is the right-hand operand. Verify that at least two values are on the stack before popping, and only then test for a zero divisor.
Hint 3
Language-level shortcuts can disagree with the spec. Floor division rounds the wrong way for negatives, and a permissive int() conversion accepts things like underscores or non-ASCII digits. Use an exact truncating division on absolute values and an explicit ASCII pattern like [+-]?[0-9]+ for literals.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a straightforward simulation with a stack. Two pieces of state are kept: stack (a list used as LIFO, O(1) push and pop) and output (values printed so far). The function walks over program.split(), which already copes with any run of whitespace and yields no tokens for an empty or blank string.
Each token is handled by exactly one branch, in this order:
- Binary operator (
+ - * /). DUP,POP,PRINT.- Integer literal, matched by the ASCII pattern
[+-]?[0-9]+. - Anything else is
INVALID_TOKEN.
Checking command names first matters: a lone + or - is an operator, while +5 or -5 is a literal. Anything that is neither falls through to the error.
Key decisions
Validate before mutating. Every branch checks operand count (and the divisor) before it changes state. When an error occurs we return (output, code) immediately. Since output is never rolled back, partial output is preserved naturally, and the stack contents at error time do not matter because they are not returned.
Operand order. The first pop is b (right), the second is a (left). So 10 4 - is 10 - 4 = 6.
Error precedence. For /, underflow wins over zero division: with fewer than two values there is no divisor to inspect, so 0 / is UNDERFLOW, while 1 0 / is ZERODIVISION. Errors are reported for the first failing token in program order.
Truncating division. Python's // floors, giving -7 // 2 == -4, but the spec wants -3. Writing int(a / b) goes through a float, which cannot represent every 64-bit integer exactly. The exact approach is:
q = abs(a) // abs(b)
q = -q if (a < 0) != (b < 0) else q
Literal parsing. int(token) inside try/except is too permissive: it accepts "1_000", surrounding whitespace and non-ASCII digits. str.isdigit() also accepts characters like "²". An explicit re.fullmatch(r"[+-]?[0-9]+", token) follows the grammar exactly.
Code
import re
_INT_RE = re.compile(r"[+-]?[0-9]+")
def _trunc_div(a: int, b: int) -> int:
q = abs(a) // abs(b)
return -q if (a < 0) != (b < 0) else q
def evaluate_stack_program(program: str) -> tuple[list[int], str | None]:
stack: list[int] = []
output: list[int] = []
binary_ops = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": _trunc_div,
}
for token in program.split():
if token in binary_ops:
if len(stack) < 2:
return output, "UNDERFLOW"
b = stack.pop()
a = stack.pop()
if token == "/" and b == 0:
return output, "ZERODIVISION"
stack.append(binary_ops[token](a, b))
elif token == "DUP":
if not stack:
return output, "UNDERFLOW"
stack.append(stack[-1])
elif token == "POP":
if not stack:
return output, "UNDERFLOW"
stack.pop()
elif token == "PRINT":
if not stack:
return output, "UNDERFLOW"
output.append(stack.pop())
elif _INT_RE.fullmatch(token):
stack.append(int(token))
else:
return output, "INVALID_TOKEN"
return output, None
A dispatch table keeps the shared operand-count logic in one place, so adding another binary operator is a one-line change.
Why it is correct
The invariant is that after processing token i without error, stack and output match the state the specification defines after i tokens. Each token maps to one branch that implements its definition, and all checks happen before any mutation, so an error never leaves a half-applied operation behind.
Complexity
- Time: O(n) for n =
len(program). Splitting is linear, each token does O(1) stack work plus a regex match proportional to its length, and arithmetic on bounded values is O(1). - Space: O(n) for the token list, the stack and the output.
Edge cases to test
| Input | Result |
|---|---|
"" or whitespace only | ([], None) |
"+" | ([], "UNDERFLOW") |
"+0 PRINT", "-0 PRINT" | ([0], None) |
"5 PRINT 3 +" | ([5], "UNDERFLOW") |
"-7 2 / PRINT" | ([-3], None) |
"7 -2 / PRINT" | ([-3], None) |
"1 0 /" | ([], "ZERODIVISION") |
"0 /" | ([], "UNDERFLOW") |
"1 dup" | ([], "INVALID_TOKEN") |
"--5", "5a", "1_0", "+-3" | INVALID_TOKEN |
"1 2 3" | ([], None) |
Common mistakes
- Swapping operand order for
-and/. - Using floor division for negative operands.
- Treating a bare
+or-as a number, or accepting--5and1_0via a permissiveint(). - Checking the zero divisor before the stack size.
- Discarding the output when an error occurs.
- Treating leftover stack values as an error.
Follow-ups worth discussing
- Control flow (
IF/ELSE/THEN, loops): switch to an instruction pointer over a token array, and pre-compute jump targets with a bracket stack so structural errors are caught before any side effects. - Subroutines: store definitions in a name-to-token-range map and use an explicit return stack instead of Python recursion, so call depth can be capped with a clean error.