ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
class Vec:
    def __init__(self, *c): self.c = c
    def __mul__(self, k): return Vec(*(x * k for x in self.c))
    __rmul__ = __mul__
    def __matmul__(self, o): return sum(a * b for a, b in zip(self.c, o.c))
    def __bool__(self): return any(self.c)
    def __repr__(self): return f"Vec{self.c}"
v = Vec(1, 2)
print(2 * v, v * 3, v @ Vec(3, 4), bool(Vec(0, 0)))
  1. A. Vec(1, 2, 1, 2) Vec(3, 6) 11 False
  2. B. Vec(2, 4) Vec(3, 6) 11 False
  3. C. TypeError
  4. D. Vec(2, 4) Vec(3, 6) 11 True

Correct answer: B. Vec(2, 4) Vec(3, 6) 11 False

2 * v: int's __mul__ returns NotImplemented for a Vec, so Python calls v.__rmul__(2). @ calls __matmul__ (here a dot product: 3 + 8 = 11). __bool__ decides truthiness.

More Python Programming questions

Exams that ask this topic