Skip to content

Instantly share code, notes, and snippets.

@MSK61
Created September 27, 2014 21:27
Show Gist options
  • Save MSK61/1997c31e01fafbaff01f to your computer and use it in GitHub Desktop.
Save MSK61/1997c31e01fafbaff01f to your computer and use it in GitHub Desktop.
class Replier:
def __init__(self, secret):
self._diff = None
self._secret = secret
def answer(self, val):
last_diff = self._diff
self._diff = abs(val - self._secret)
return (-1 if last_diff and self._diff > last_diff else 1) if \
self._diff else 0
def find2(rep, N):
"""Find the secret in ~ 2 lg N guesses."""
lo = 1
hi = N
while lo < hi:
if not rep.answer(lo):
return lo
ans = rep.answer(hi)
if not ans:
return hi
mid = (lo + hi) / 2
if ans > 0:
lo = mid
else:
hi = mid
return lo
def find(rep, N):
"""Find the secret in ~ lg N guesses."""
lo = 1
hi = N
guess = 1
decision_pt = hi
if not rep.answer(1):
return lo
while hi - lo > 1:
guess = lo + hi - guess
ans = rep.answer(guess)
if not ans:
return ans
mid = (lo + hi) / 2
if decision_pt == lo:
if ans > 0:
hi = mid
else:
lo = mid
decision_pt = hi
else:
if ans > 0:
lo = mid
else:
hi = mid
decision_pt = lo
return hi if rep.answer(lo) else lo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment