ProgrammingHardTCS NQT · Accenture

A list a is sorted in ascending order and may contain duplicates. Using bisect_left and bisect_right from the bisect module, which expression gives the number of elements of a that are equal to x?

  1. A. bisect_left(a, x) - bisect_right(a, x)
  2. B. bisect(a, x) - 1
  3. C. bisect_right(a, x) - bisect_left(a, x)
  4. D. a.index(x) + 1

Correct answer: C. bisect_right(a, x) - bisect_left(a, x)

bisect_right minus bisect_left counts the positions occupied by x in a sorted list. The other options are negative, off by one, or return only the first index.

More Python Programming questions

Exams that ask this topic