Problem 389715 · easy · Level 03 Linear Management & Searching

Which Floor Is the Cat On?

binary search · higher-order functions

A cat is hiding on one floor of a tower whose floors are numbered 1..n. You may ask the caretaker about any floor g, and the reply is the function call compare(g):

  • 0: the cat is on floor g;
  • -1: floor g is above the cat;
  • 1: floor g is below the cat.

Given n and compare, return the cat's floor. The tests build compare from the hidden floor secret, e.g. lambda g: (secret > g) - (secret < g).

Examples

Input:  n = 20, compare = lambda g: (13 > g) - (13 < g)
Output: 13

Input:  n = 1, compare = lambda g: 0
Output: 1

Constraints

  • Your function may call compare at most 40 times; trying values one by one will time out.

Goals

  • Drive a binary search with feedback from a function instead of list values
  • Interpret a three-way comparison result correctly
Starting Python…