CODING CHALLENGE · N°68

Read the Codebase, Fix the Bug

Medium AI EngineeringCode ReviewDebugging

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.

EXAMPLE 1
Input rpn(['3', '4', '+'])
Output 7.0
addition is fine — order does not matter, so this already passes
EXAMPLE 2
Input rpn(['5', '2', '-'])
Output 3.0
the bug: _apply returns b - a = 2 - 5 = -3. Correct is a - b = 3
EXAMPLE 3
Input rpn(['10', '2', '3', '-', '*'])
Output -10.0
10 * (2 - 3) = -10 — a multi-op expression that only works once subtraction is fixed
CONSTRAINTS
  • 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 _apply so "-" returns a - b and "/" returns a / 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.
SOLVE IT YOURSELF

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.

YOUR TASK

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.

HINTS — 4 IDEAS
  1. 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.
  2. For ["5","2","-"], the stack is [5, 2]; b=2, a=5. You want a - b = 5 - 2 = 3.
  3. The current _apply returns b - a and b / a — both reversed. Swap them to a - b and a / b.
  4. Addition and multiplication are commutative, which is why only "-" and "/" show the bug.
CPython · WebAssembly

Explore the topic

See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.