ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def rpn(tokens):
    st = []
    for t in tokens:
        if t in ('+', '-', '*', '/'):
            b = st.pop()
            a = 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(['-7', '2', '/']), rpn(['7', '-2', '/']), -7 // 2)
  1. A. -3 -3 -4
  2. B. -4 -4 -4
  3. C. -3 -3 -3
  4. D. -3 -4 -4

Correct answer: A. -3 -3 -4

int(a / b) truncates toward zero, which is what the RPN evaluation needs, so -7 / 2 gives -3. Python's // floors toward minus infinity, so -7 // 2 is -4, which is the trap.

More Python Programming questions

Exams that ask this topic