ProgrammingHardTCS NQT · Wipro pattern

What is printed?

What is printed?
def first_true(lo, hi, ok):
    while lo < hi:
        mid = (lo + hi) // 2
        if ok(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo
print(first_true(0, 100, lambda x: x * x >= 2024), first_true(5, 5, lambda x: True))
  1. A. 44 5
  2. B. 45 6
  3. C. 45 5
  4. D. 46 5

Correct answer: C. 45 5

Binary search on a monotone predicate returns the first true point. 45 squared is 2025, the first square at or above 2024, and a range of one value returns its lower bound.

More Python Programming questions

Exams that ask this topic