ProgrammingVery hardProduct company OA
What is printed?
What is printed?
x = 1
class K:
x = 2
a = [x for _ in range(2)]
b = [x * i for i in range(x + 1)]
def m(self): return x
print(K.a, K.b, K().m(), K.x)- A. [1, 1] [0, 1, 2] 1 2
- B. [2, 2] [0, 2, 4] 2 2
- C. [1, 1] [0, 1] 1 2
- D. [2, 2] [0, 2, 4] 1 2
Correct answer: A. [1, 1] [0, 1, 2] 1 2
A class body is not an enclosing scope for functions or comprehensions defined inside it. Only the FIRST iterable of a comprehension is evaluated in the class body, so range(x + 1) uses the class-level x = 2 → range(3). The element expressions run in the comprehension's own scope, which skips the class namespace and finds the global x = 1: a = [1, 1], b = [0, 1, 2]. The method m likewise returns the global 1, while K.x is 2. '[0, 1]' forgets that the outermost iterable does see the class variable.
More Python Programming questions
- What is printed? python data = [5, 3, 8, 1] out = [] while (n := len(data)) > 1: first, data = data data[-1] += first out.append((n…
- What is printed? python from functools import lrucache @lrucache(maxsize=None) def path(n): return [0] if n == 0 else path(n - 1) + [n] p…
- What is printed? python class Seq: def init(self, n): self.n = n; self.calls = 0 def getitem(self, i): self.calls += 1 if i >= self.n…
- What is printed? python import heapq tasks = [(2, "write"), (1, "test"), (2, "ship"), (1, "plan")] h = [] for i, (p, name) in…
- What is printed? python x = -13 print(x >> 2, x // 4, ~x, x & 0xF, bin(x & 0xFF).count("1"), (-x) >> 2)
- What is printed? python def chain(nums, divisors): g = (n for n in nums) for d in divisors: g = (n for n in g if n % d) return list(g)…