ProgrammingHardCognizant GenC · TCS NQT

What is printed?

What is printed?
class Q:
    def __init__(self):
        self.i, self.o = [], []
    def push(self, x):
        self.i.append(x)
    def pop(self):
        if not self.o:
            while self.i:
                self.o.append(self.i.pop())
        return self.o.pop()
q = Q()
for x in [1, 2, 3]:
    q.push(x)
a = q.pop()
q.push(4)
print(a, q.pop(), q.pop(), q.pop())
  1. A. 1 2 3 4
  2. B. 1 3 2 4
  3. C. 3 1 2 4
  4. D. 1 2 4 3

Correct answer: A. 1 2 3 4

The input stack moves to the output stack only when the output is empty, which gives first-in first-out order. After the first pop returns 1, the remaining pops return 2, 3 and 4.

More Python Programming questions

Exams that ask this topic