Data Structures & AlgorithmsModerateTCS NQT · stack basics

Problem: What is the value of the reverse Polish expression '2 1 + 3 '? Run the stack code.

Problem: What is the value of the reverse Polish expression '2 1 + 3 *'? Run the stack code.
tokens = '2 1 + 3 *'.split()
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))
print(st[0])
What is printed?
  1. A. 7
  2. B. 5
  3. C. 9
  4. D. 11

Correct answer: C. 9

A stack evaluates postfix left to right: 2 1 + leaves 3, then 3 3 * leaves 9. Reading the tokens as infix with precedence (2 + 1 × 3) gives the tempting 5, and popping operands in the wrong order only matters for - and /.

More Coding Interview Problems questions

Exams that ask this topic