ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

What is printed?
import bisect
a = [(1, 'x'), (3, 'y'), (3, 'z'), (7, 'w')]
i = bisect.bisect_left(a, 3, key=lambda p: p[0])
j = bisect.bisect_right(a, 3, key=lambda p: p[0])
print(i, j, a[i:j])
  1. A. 1 2 [(3, 'y')]
  2. B. 0 3 [(1, 'x'), (3, 'y'), (3, 'z')]
  3. C. 1 4 [(3, 'y'), (3, 'z'), (7, 'w')]
  4. D. 1 3 [(3, 'y'), (3, 'z')]

Correct answer: D. 1 3 [(3, 'y'), (3, 'z')]

The key argument, available from Python 3.10, makes bisect compare only the first field. Left gives index 1 and right gives index 3, so the slice holds both 3s.

More Python Programming questions

Exams that ask this topic