Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

Evaluate the postfix expression with single-digit operands. What is printed?

Evaluate the postfix expression with single-digit operands. What is printed?
st = []
for t in "62/3-42*+":
    if t.isdigit(): st.append(int(t))
    else:
        b, a = st.pop(), st.pop()
        st.append({'+': a + b, '-': a - b, '*': a * b, '/': a // b}[t])
print(st)
  1. A. [8]
  2. B. [2]
  3. C. [-8]
  4. D. [6]

Correct answer: A. [8]

6/2 = 3, 3 − 3 = 0, 4·2 = 8, 0 + 8 = 8. The second popped value is the left operand; popping the other way round gives 2/6 = 0 and different results.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic