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())
  1. A. 1 [3, 6] 2
  2. B. 11 [13, 16] 17
  3. C. 1 [13, 16] 2
  4. 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

Exams that ask this topic