ProgrammingVery hardCodeforces-style · placement coding round

What is printed?

What is printed?
import bisect
def closest(a, x):
    i = bisect.bisect_left(a, x)
    cands = a[max(i - 1, 0):i + 1]
    return min(cands, key=lambda v: abs(v - x))
print(closest([1, 4, 6, 10], 5), closest([1, 4, 6, 10], 12), closest([1, 4, 6, 10], 0))
  1. A. 6 10 1
  2. B. 4 10 1
  3. C. 4 10 0
  4. D. 4 12 1

Correct answer: B. 4 10 1

bisect_left finds the neighbours of x, and min returns the first candidate among equal distances. For 5, both 4 and 6 are one away, so 4 wins.

More Python Programming questions

Exams that ask this topic