ProgrammingVery hardProduct company OA
What is printed?
What is printed?
def counter():
n = 0
def inc(k=1):
nonlocal n
n += k
return n
return inc
c1, c2 = counter(), counter()
g = (c1(i) for i in range(1, 4))
c1(10)
first = next(g)
c2(first)
print(first, list(g), c2())- A. 1 [3, 6] 2
- B. 11 [13, 16] 17
- C. 1 [13, 16] 2
- D. 11 [13, 16] 12
Correct answer: D. 11 [13, 16] 12
Each counter() call owns a separate cell n. A generator expression runs nothing until it is advanced, so c1(10) executes first (n = 10); next(g) then calls c1(1) → 11. c2 has its own n: c2(11) → 11. Draining g calls c1(2) → 13 and c1(3) → 16, and c2() adds the default 1 → 12. Output: 11 [13, 16] 12. '1 [3, 6] 2' assumes the generator body ran eagerly when g was created.
More Python Programming questions
- What is printed? python def f(): out = [] for i in range(4): try: if i == 1: continue if i == 2: raise KeyError(i) if i == 3: return out…
- What is printed? python rows = [("x", 2), ("y", 1), ("z", 2), ("w", 1), ("v", 3)] a = sorted(rows, key=lambda r: r[1], reverse=True) b =…
- What is printed? python class P: def init(self, x, y): self.x, self.y = x, y def eq(self, o): return self.x == o.x def hash(self): return…
- What is printed? python it = iter(range(10)) a = list(zip(it, "ab")) b = next(it) c = [x for x in it if next(it, 0) % 3] print(a, b, c)
- What is printed? python def tag(t): print("make", t, end=" ") def deco(fn): print("wrap", t, end=" ") def inner(a): return f"<{t}>" +…
- What is printed? python 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…