ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
class M:
def __init__(self, v): self.v = v
def __add__(self, o):
return M(self.v + (o.v if isinstance(o, M) else o))
ms = [M(1), M(2), M(3)]
print(sum(ms, M(0)).v, end=" ")
try:
print(sum(ms).v)
except TypeError:
print("TypeError")- A. 6 6
- B. 6 TypeError
- C. TypeError
- D. 6 0
Correct answer: B. 6 TypeError
sum(ms, M(0)) computes M(0) + M(1) + M(2) + M(3) using M.__add__, giving v = 6. sum(ms) starts from the integer 0, so the first step is 0 + M(1): int.__add__ returns NotImplemented, and M has no __radd__ to fall back on, so TypeError is raised. Adding __radd__ would make the plain sum work.
More Python Programming questions
- What is printed? python print(f"{3.14159:.2f}|{42:>5}|{'ab':^6}|{255:#x}|{1234567:,}")
- What is printed? python grid = [[0, 0]] 2 copy1 = list(grid) copy2 = [row[:] for row in grid] grid[0][0] = 1 grid[1] = [5, 5] print(copy1…
- What is printed? python vals = iter([3, 1, 0, 4, 0]) print(list(iter(lambda: next(vals), 0)), list(vals))
- What is printed? python class Acc: def init(self): self.items = [] def iadd(self, v): self.items.append(v) a = Acc() b = a a += 1 print(a…
- What is printed? python def f(): log = [] try: log.append("t") raise ValueError("v") except ValueError as e: log.append("e") raise…
- What is printed? python it = iter(range(10)) print(5 in it, next(it), 2 in it, list(it), 9 in range(10))