ProgrammingVery hardProduct company OA
What is printed?
What is printed?
class V:
def __init__(self, n, log): self.n, self.log = n, log
def __add__(self, o): self.log.append("add"); return V(self.n + getattr(o, "n", o), self.log)
def __radd__(self, o): self.log.append("radd"); return V(self.n + o, self.log)
def __iadd__(self, o): self.log.append("iadd"); self.n += getattr(o, "n", o); return self
log = []
a = V(1, log); b = a
a += 2
a = a + a
b = 5 + b
s = sum([a, b])
print(a.n, b.n, s.n, " ".join(log))- A. 6 6 12 iadd add radd add
- B. 6 8 14 iadd add radd add add
- C. 6 11 17 iadd add radd radd add
- D. 6 8 14 iadd add radd radd add
Correct answer: D. 6 8 14 iadd add radd radd add
a += 2 uses __iadd__, mutating the shared object to 3 (b sees it). a = a + a creates a NEW V(6); b still refers to the old V(3). 5 + b: int.__add__ returns NotImplemented, so Python tries b.__radd__(5) → V(8). sum starts from the int 0, so its first step 0 + a is another __radd__, and the second step V + V is __add__: 6 + 8 = 14. Log: iadd add radd radd add. Forgetting sum's implicit start value 0 loses the second radd.
More Python Programming questions
- What is printed? python log = [] def t(x): log.append(x); return x def f(a, b=t("d1"), args, c=t("d2"), kw): return a, b, args, c…
- What is printed? python d = dict.fromkeys("ab", []) d["a"].append(1) d["b"] = d["b"] + [2] d["a"] += [3] g = [[]] 2 + [[] for in range(2)]…
- A log pipeline must remove duplicate event ids from a list xs of n = 2·10⁵ integers while keeping the order of first occurrence. Four…
- What is printed? python class Base: registry = [] def initsubclass(cls, kw): cls.registry.append(cls.name) cls.tag = kw.get("tag"…
- What is printed? python class CM: def init(self, name, swallow): self.name, self.swallow = name, swallow def enter(self): print("in" +…
- What is printed? python import bisect a = [1, 3, 3, 3, 7] i, j = bisect.bisectleft(a, 3), bisect.bisectright(a, 3) bisect.insortleft(a…