Curated · Queues

MCQ · 1 mark · Problem PROG-DSTR-0348

Consider the following Python code.
from collections import deque
q = deque()
for x in [4, 7, 1, 9]:
    q.append(x)
q.append(q.popleft() + q.popleft())
q.appendleft(q.pop())
print(list(q))
What does it print?
  1. A
    [1, 9, 11]
  2. B
    [10, 4, 7]
  3. C
    [11, 1, 9]
  4. D
    [11, 9, 1]

Solve it on GATE DA practice →More Basic Data Structures problems

Show the worked solution\[\boxed{\text{append, pop: rear end}\qquad \text{appendleft, popleft: front end}}\]After the loop the deque is \([4, 7, 1, 9]\), front on the left.The two popleft calls remove 4 and 7 from the front, and their sum 11 is appended at the rear: \([1, 9, 11]\).pop removes 11 from the rear and appendleft puts it at the front: \([11, 1, 9]\).Treating popleft like a stack pop (removing 9 and 1) gives the distractor \([10, 4, 7]\).Answer: C

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com