Asked at Squarepoint Capital
Theory: Parsing and Data HygieneRead the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.
Available in Python and C++. You are solving it in Python. Switch to C++
Implement run_program(lines), a small stack machine. It takes a sequence of
strings, one command per line, and runs them on a stack of integers. It stops
at the first bad instruction and reports which line it was. Pricing
expression languages, config languages and protocol test harnesses use the
same shape.
Tokens are separated by whitespace. The commands:
PUSH n: push the integer n. Exactly one argument; valid arguments
are an optional leading - followed by one or more digits (so -4 and
007 are valid, +5, 1_0 and x are not).POP: discard the top value (needs 1 value on the stack).DUP: push a copy of the top value (needs 1).SWAP: exchange the top two values (needs 2).ADD, SUB, MUL: pop the top value a, then b, and push
b + a, b - a, b * a respectively (each needs 2).Any violation aborts immediately with an error result carrying the line
number, counted from 1: a blank line, an unknown command, a wrong argument
count, a bad PUSH argument, or a stack underflow. Commands are
case-sensitive. If every line executes, return a success result carrying the
remaining stack values, bottom to top.
def run_program(lines: list[str]) -> tuple[str, tuple[int, ...]] | tuple[str, int]: ...
The error result is ("ERROR", line_number). The success result is
("OK", stack) where stack is a tuple of the remaining values, bottom to
top (an empty program returns ("OK", ())).
run_program(["PUSH 3", "PUSH 4", "ADD", "PUSH 2", "MUL"])
# ('OK', (14,)) (3 + 4) * 2
run_program(["PUSH 5", "DUP", "SUB", "POP", "POP"])
# ('ERROR', 5) 5 - 5 = 0 is popped, then the second POP underflows