ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
import bisect
def pairs_le(a, d):
    a = sorted(a)
    c = 0
    for i, x in enumerate(a):
        j = bisect.bisect_right(a, x + d, i + 1)
        c += j - (i + 1)
    return c
print(pairs_le([1, 5, 3, 8, 4], 2))
  1. A. 3
  2. B. 4
  3. C. 5
  4. D. 6

Correct answer: B. 4

After sorting, each value counts the later values within distance d, found with bisect_right and a lower bound. The pairs (1,3), (3,4), (3,5) and (4,5) give 4.

More Python Programming questions

Exams that ask this topic