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)))- A. Vec(1, 2, 1, 2) Vec(3, 6) 11 False
- B. Vec(2, 4) Vec(3, 6) 11 False
- C. TypeError
- 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
- What is printed? python class Ordered: def init(self, v): self.v = v def lt(self, o): print("lt", end=" ") return self.v < o.v def…
- What is printed? python import functools @functools.totalordering class V: def init(self, n): self.n = n def eq(self, o): return self.n ==…
- What is printed? python def f(): l = [] for i in range(3): try: if i == 0: raise ValueError l.append(i) except ValueError: l.append("v")…
- What is printed? python def risky(n): if n == 1: raise KeyError(n) if n == 2: raise IndexError(n) return n res = [] for n in range(4)…
- What is printed? python class E(Exception): def str(self): return "custom" try: try: raise E("orig") except E as e: raise…
- What is printed? python def f(x): try: return int(x) except ValueError: return float(x) except TypeError: return -1 print(f("3")…