Read the Codebase, Fix the Bug
The real skill an AI can’t fake for you: drop into unfamiliar code, trace how the pieces call each other, and fix the one that’s wrong without breaking the rest. Here a reverse-Polish calculator is spread across three functions and gets subtraction and division backwards. Read how operands flow from the loop into the math, then fix it at the source.
The problem
The starter code is a small RPN (reverse-Polish) evaluator in three functions: _is_op classifies a token, rpn runs the stack loop, and _apply does the arithmetic. rpn pops the top of the stack into b and the next into a, then calls _apply(op, a, b) — so for ["5", "2", "-"] it means a - b = 5 - 2 = 3. But _apply computes subtraction and division with the operands reversed, so those two operators give the wrong answer. Trace the operand order from rpn into _apply and fix the two buggy branches. Return the final value on the stack.
rpn(['3', '4', '+'])7.0rpn(['5', '2', '-'])3.0rpn(['10', '2', '3', '-', '*'])-10.0- Do not change the operand order in
rpn— it is correct (b= top of stack,a= the one below). The bug is in_apply. - Fix
_applyso"-"returnsa - band"/"returnsa / b. Leave"+"and"*"alone. - Non-operator tokens are pushed as
float; the result is the single value left on the stack. - Assume well-formed input — no need to handle empty stacks or bad tokens.
Your turn — write it
Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.
This RPN evaluator gets subtraction and division backwards. Read how rpn feeds operands into _apply, then fix the two reversed branches in _apply — without touching rpn’s (correct) pop order.
- Start in rpn: it pops b (top) then a (next), then calls _apply(op, a, b). So inside _apply, a is the left operand and b is the right.
- For ["5","2","-"], the stack is [5, 2]; b=2, a=5. You want a - b = 5 - 2 = 3.
- The current _apply returns b - a and b / a — both reversed. Swap them to a - b and a / b.
- Addition and multiplication are commutative, which is why only "-" and "/" show the bug.
Explore the topic
See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.