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)
  1. A. True False [0, 1, 4, 9] 12
  2. B. True False [0, 1, 4, 9] 13
  3. C. True False [0, 1, 4, 9] 14
  4. 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

Exams that ask this topic