—
Evaluate postfix arithmetic with a stack
Tutor me on https://mlprep.iwase.dev/item/prog-ds-postfix-stack/. This is a screening item. If window.mlPrepAgent is available, read attempts for item prog-ds-postfix-stack before tutoring. Inspect my attempt, keep the item ID, and do not reveal the full answer first. After a real attempt, append its record with recorded_by agent, include agent_session_id when available, and read it back.Problem
Implement evaluate_postfix(tokens) for a valid postfix expression whose
tokens are integer literals or +, -, and *. For an operator, pop the
right operand and then the left operand. Return the final integer.
Reveal answer or reference solution
Push integers. For an operator, pop right, pop left, compute
left operator right, and push the result. Subtraction makes the pop
order observable. The algorithm is time and worst-case space.
def evaluate_postfix(tokens: list[str]) -> int:
stack: list[int] = []
for token in tokens:
if token not in {"+", "-", "*"}:
stack.append(int(token))
continue
right = stack.pop()
left = stack.pop()
if token == "+":
stack.append(left + right)
elif token == "-":
stack.append(left - right)
else:
stack.append(left * right)
return stack[0]Public tests
evaluate_postfix(["2", "3", "+"])→5evaluate_postfix(["7", "2", "-"])→5evaluate_postfix(["2", "3", "+", "4", "*"])→20evaluate_postfix(["5"])→5
Previous attempts
Loading attempts saved in this browser…