Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Evaluate an expression in Reverse Polish notation; division truncates toward zero.

Problem: Evaluate an expression in Reverse Polish notation; division truncates toward zero.
def rpn(tokens):
    st = []
    for t in tokens:
        if t in "+-*/":
            b, a = st.pop(), st.pop()
            if t == '+': st.append(a + b)
            elif t == '-': st.append(a - b)
            elif t == '*': st.append(a * b)
            else: st.append(int(a / b))
        else:
            st.append(int(t))
    return st[0]
print(rpn(["4", "13", "5", "/", "+"]), rpn(["7", "-3", "/"]), 7 // -3)
What is printed?
  1. A. 6 -3 -3
  2. B. 6 -2 -2
  3. C. 5 -2 -3
  4. D. 6 -2 -3

Correct answer: D. 6 -2 -3

13 / 5 = 2, then 4 + 2 = 6. For 7 / −3 the problem wants truncation toward zero (−2), as in C/Java; Python's // floors to −3, which is why int(a / b) is used. The second popped value is the left operand. O(n).

More Coding Interview Problems questions

Exams that ask this topic