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)- A. [1, 5, 20, 21]
- B. [1, 5, 6, 20, 20, 21]
- C. [1, 5, 20, 20, 21]
- 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
- What is printed? python def reg(name, seen={}, order=[]): if name not in seen: seen[name] = len(order) order = order + [name] return…
- What is printed? python def bucket(x, w): return x // w, x % w, int(x / w), -(-x // w) print(bucket(-7, 3), bucket(7, -3))
- What is printed? python d = {"b": 1, "a": 2, "c": 3} d["a"] = 9 d.update(b=7, d=4) d["c"] = d.pop("c") d.setdefault("a", 0) e = {d, "b"…
- What is printed? python a = [1, 2]; b = a; c = a[:] t = (a, c) a += [3] b = b + [4] c = 2 print(t[0] is a, b is a, t[1] is c, len(t[0])…
- What is printed? python a = list(range(8)) b = a[::2] a[1::2] = b[::-1] a[2:5] = [] del a[-2:] b[0] = 99 print(a, b)
- What is printed? python class Meter: unit = "m" def init(self): self.dict["v"] = 1 def getattr(self, name): return name.upper() def…