ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
class Node:
def __init__(self, v, nxt=None): self.v, self.nxt = v, nxt
def __iter__(self):
n = self
while n:
yield n.v
n = n.nxt
lst = Node(1, Node(2, Node(3)))
def rev(n, prev=None):
while n:
n.nxt, prev, n = prev, n, n.nxt
return prev
print(list(lst), list(rev(lst)), list(lst))- A. [1, 2, 3] [3, 2, 1] [1, 2, 3]
- B. [1, 2, 3] [3, 2, 1] [1]
- C. [1, 2, 3] [3, 2, 1] [3, 2, 1]
- D. [1, 2, 3] [1] [1]
Correct answer: B. [1, 2, 3] [3, 2, 1] [1]
The tuple assignment evaluates (prev, n, n.nxt) first and then assigns n.nxt, prev, n left to right, which correctly reverses the list in place. Afterwards the old head (1) is the tail, so iterating from it yields only [1].
More Python Programming questions
- What is printed? python import heapq h = [5, 1, 4] heapq.heapify(h) heapq.heappush(h, 0) small = heapq.heappop(h) print(small, h[0]…
- What is printed? python from collections import deque d = deque([1, 2, 3], maxlen=3) d.append(4) d.appendleft(0) d.rotate(1)…
- What is printed? python from collections import namedtuple P = namedtuple("P", "x y", defaults=[0]) p = P(1) q = p.replace(y=5) print(p…
- What is printed? python from dataclasses import dataclass, field @dataclass class Item: name: str tags: list = field(defaultfactory=list)…
- What is printed? python from dataclasses import dataclass @dataclass(frozen=True) class Pt: x: int y: int = 0 p = Pt(1) try: p.x = 5…
- What is printed? python nums = [1, 2, 3, 4, 5, 6] evens = list(filter(lambda n: n % 2 == 0, nums)) total = sum(n n for n in nums if n % 2)…