ProgrammingVery hardProduct company OA

What is printed?

What is printed?
def inner():
    x = yield 1
    y = yield x + 1
    return x * y
def outer():
    r = yield from inner()
    yield r
    yield from range(r, r + 2)
g = outer()
out = [next(g), g.send(4), g.send(5)]
out += list(g)
print(out)
  1. A. [1, 5, 20, 21]
  2. B. [1, 5, 6, 20, 20, 21]
  3. C. [1, 5, 20, 20, 21]
  4. D. [1, 5, 20, 20, 21, 22]

Correct answer: C. [1, 5, 20, 20, 21]

yield from forwards send() to the inner generator and evaluates to its return value. next → 1; send(4) makes x = 4 and yields 5; send(5) makes y = 5, inner returns 20 (carried by StopIteration), so r = 20 and outer immediately yields 20 as the result of that same send. list(g) then drains range(20, 22) → 20, 21. Result [1, 5, 20, 20, 21]. Dropping the duplicate 20 forgets that 'yield r' and the range both produce 20.

More Python Programming questions

Exams that ask this topic