Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Evaluate a reverse-Polish expression. The specification says division must truncate toward zero (as in C or Java).

Problem: Evaluate a reverse-Polish expression. The specification says division must truncate toward zero (as in C or Java).
def rpn(tokens):
    st = []
    for t in tokens:
        if t in "+-*/":
            b, a = st.pop(), st.pop()
            st.append(a + b if t == '+' else a - b if t == '-' else a * b if t == '*' else a // b)
        else:
            st.append(int(t))
    return st[0]
print(rpn(["7", "-3", "/", "2", "*"]))
What is printed?
  1. A. -4
  2. B. -6
  3. C. -5
  4. D. -3

Correct answer: B. -6

Python's // floors, so 7 // −3 = −3 (not −2) and the result is −3 × 2 = −6. Truncation toward zero would give −2 × 2 = −4, so this code violates the spec for mixed signs; int(a / b) fixes it.

More Coding Interview Problems questions

Exams that ask this topic