ProgrammingVery hardProduct company OA
What is printed?
What is printed?
class Seq:
def __init__(self, n): self.n = n; self.calls = 0
def __getitem__(self, i):
self.calls += 1
if i >= self.n: raise IndexError
return i * i
s = Seq(4)
r1 = 9 in s
r2 = 5 in s
r3 = list(s)
print(r1, r2, r3, s.calls)- A. True False [0, 1, 4, 9] 12
- B. True False [0, 1, 4, 9] 13
- C. True False [0, 1, 4, 9] 14
- D. True False [0, 1, 4, 9] 8
Correct answer: C. True False [0, 1, 4, 9] 14
With no __iter__ or __contains__, Python falls back to the old sequence protocol: it calls __getitem__(0), (1), (2)… until IndexError. '9 in s' stops as soon as it finds 9 at i = 3 → 4 calls. '5 in s' never matches, so it needs the failing call at i = 4 as well → 5 calls. list(s) also needs the terminating IndexError → 5 calls. Total 14. Counting 12 forgets the two calls that raise IndexError.
More Python Programming questions
- What is printed? python import heapq tasks = [(2, "write"), (1, "test"), (2, "ship"), (1, "plan")] h = [] for i, (p, name) in…
- What is printed? python x = -13 print(x >> 2, x // 4, ~x, x & 0xF, bin(x & 0xFF).count("1"), (-x) >> 2)
- What is printed? python def chain(nums, divisors): g = (n for n in nums) for d in divisors: g = (n for n in g if n % d) return list(g)…
- What is printed? python class V: def init(self, n, log): self.n, self.log = n, log def add(self, o): self.log.append("add"); return…
- 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)]…