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?
- A. bisect_left(a, x) - bisect_right(a, x)
- B. bisect(a, x) - 1
- C. bisect_right(a, x) - bisect_left(a, x)
- 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
- A Python list q holds n items. A loop repeatedly does x = q.pop(0) until q is empty. What is the total time cost of the loop in big-O terms?
- What is printed? python def rob(a): p, c = 0, 0 for x in a: p, c = c, max(c, p + x) return c print(rob([2, 7, 9, 3, 1]), rob([5]), rob([]))
- What is printed? python def ed(a, b): prev = list(range(len(b) + 1)) for i in range(1, len(a) + 1): cur = [i] + [0] len(b) for j in…
- What is printed? python def minlen(a, t): best = float('inf') s = 0 l = 0 for r, x in enumerate(a): s += x while s >= t: best = min(best…
- What is printed? python import heapq def kthlargest(a, k): h = [] for x in a: heapq.heappush(h, x) if len(h) > k: heapq.heappop(h) return…
- What is printed? python from collections import deque def winmax(a, k): dq = deque() out = [] for i, x in enumerate(a): while dq and…