Typed Value Stack Interpreter with Mixed Addition
Stacks & QueuesAuto-graded · 19 test casesLast updated
Simulate a stack machine whose values are tagged ints or strings, where ADD sums two ints or concatenates otherwise, and return the printed lines.
Tagged Stack Machine
You are simulating a tiny virtual machine with one stack. Each value on the stack is either an integer or a string. These are always distinct: the integer 7 and the string "7" are different values, even though they look alike. A string made only of digits is still a string.
The program is given already parsed, as a list of instructions executed in order against a single stack that starts empty. Each instruction is a list:
| Instruction | Meaning |
|---|---|
["PUSH", "INT", n] | Push the integer n. |
["PUSH", "STRING", s] | Push the string s (it may be empty). |
["POP"] | Remove the top value and discard it. |
["POP_AND_PRINT"] | Remove the top value and record its text form as one output line. |
["ADD"] | Remove the top two values and push one combined value (see below). |
ADD rule
Let top be the value on top of the stack and deep the value directly beneath it (the one pushed earlier). Remove both, then push:
- If both are integers: the integer
deep + top. - Otherwise (at least one is a string): turn any integer operand into its decimal text (a negative integer keeps its
-sign), then push the stringdeep_text + top_text. The earlier-pushed value comes first.
The result of ADD is a string whenever either operand is a string, even if the other is an empty string.
Printing
POP_AND_PRINT records the value as plain text: integers in ordinary decimal form (with - if negative), strings exactly as their characters, with no quotes. An empty string is recorded as an empty line (the empty string "").
Task
Implement a function that runs the whole program and returns a list of strings: the recorded lines from every POP_AND_PRINT, in execution order. If nothing is printed, return an empty list.
Constraints
- 1 ≤ number of instructions ≤ 10^5.
- Integer operands and every intermediate integer sum fit in a signed 64-bit integer.
- String operands consist of printable ASCII characters, may be empty, and may consist of digits.
- The total length of all string values ever created during execution is at most 10^6 characters.
- The program is valid:
POPandPOP_AND_PRINTonly occur when the stack is non-empty, andADDonly occurs when the stack has at least two values.
Examples
Example 1
Input: simulate_typed_stack([['PUSH', 'INT', 7], ['PUSH', 'INT', 7], ['ADD'], ['POP_AND_PRINT'], ['PUSH', 'INT', 7], ['PUSH', 'STRING', '7'], ['ADD'], ['POP_AND_PRINT'], ['PUSH', 'STRING', 'ab'], ['PUSH', 'STRING', 'cd'], ['ADD'], ['POP_AND_PRINT']])
Output: ['14', '77', 'abcd']
Example 2
Input: simulate_typed_stack([['PUSH', 'STRING', '10'], ['PUSH', 'INT', -2], ['ADD'], ['POP_AND_PRINT'], ['PUSH', 'INT', -5], ['PUSH', 'INT', 8], ['ADD'], ['POP_AND_PRINT']])
Output: ['10-2', '3']
Example 3
Input: simulate_typed_stack([['PUSH', 'STRING', ''], ['PUSH', 'STRING', 'x'], ['ADD'], ['POP_AND_PRINT'], ['PUSH', 'INT', 0], ['POP'], ['PUSH', 'STRING', '007'], ['POP_AND_PRINT']])
Output: ['x', '007']
Hints
Hint 1
Store each stack entry together with an explicit type tag instead of guessing the type from its contents; a digit-only string must stay a string.
Hint 2
For ADD, pop the top first and the deeper value second. Only if both tags are INT do you add numerically; in every other case convert ints with str() and concatenate deeper + top.
Hint 3
The result of ADD must be tagged STRING whenever any operand was a string, so later ADDs keep concatenating. Printing uses plain str(value), with no quotes.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The stack logic is simple; the key is keeping the type of each value explicit. Every stack entry is stored as a pair (kind, value) where kind is "INT" or "STRING". The tag comes from the instruction itself, so we never infer a type by looking at the contents. This keeps the string "7" distinct from the integer 7.
Processing each instruction in order:
- PUSH: append
(kind, value)taken from the instruction. - POP: pop and discard.
- POP_AND_PRINT: pop the entry and append
str(value)to the output list. Integers print in decimal, strings print as raw text. - ADD: pop the top entry first, then the deeper one. If both are
INT, push("INT", deep + top). Otherwise convert any integer operand withstr()and push("STRING", deep_text + top_text).
Why it is correct
- Values only get created by PUSH, which copies the given tag, or by ADD, which sets the tag explicitly. A value can therefore never change type except by the ADD rule.
- "At least one string" is exactly the complement of "both integers", so the if/else covers all four tag combinations.
- Popping the top first and then the deeper value means
deep + topplaces the earlier-pushed value first, as required. - Printing with
strgives decimal digits for integers (including a leading-) and the raw characters for strings, with no quotes. An empty string yields an empty line.
Complexity
- Time: O(n + L), where n is the number of instructions and L the total length of all strings created (string concatenation copies, but L is bounded by 10^6).
- Space: O(n + L) for the stack and the output.
Reference solution
from typing import List
def simulate_typed_stack(program: List[List[object]]) -> List[str]:
stack = []
output = []
for ins in program:
op = ins[0]
if op == "PUSH":
stack.append((ins[1], ins[2]))
elif op == "POP":
stack.pop()
elif op == "POP_AND_PRINT":
_, value = stack.pop()
output.append(str(value))
else: # ADD
top_kind, top_val = stack.pop()
deep_kind, deep_val = stack.pop()
if deep_kind == "INT" and top_kind == "INT":
stack.append(("INT", deep_val + top_val))
else:
left = str(deep_val) if deep_kind == "INT" else deep_val
right = str(top_val) if top_kind == "INT" else top_val
stack.append(("STRING", left + right))
return output