I am trying to implement a binary search to guess a number between 0 and 255 (both inclusive). My guess would be analyzed by a liar
function which returns 1
if the key to find is greater than my guess, -1
if the key is less than my guess and 0
if I guessed the right number. However the liar function can lie up to 8 times.
Now the game is controlled by a bigger program (see this repo) which terminates the game as soon as the liar returns 0
, so in writing my binary search I don't need to account for an end condition, I just keep guessing till the liar runs out of lies and finally return 0
making the game runner stop everything.
This is my binary search:
import random
from typing import Callable
def Main(rng: random.Random, liar: Callable[[int], int]):
low = high = guess = res = 0
def makeAguess(counter):
nonlocal low, high, guess, res
if (counter % 8) == 0:
low = 0
high = 255
counter = 0
guess = (low + high) // 2
res = liar( guess );
if res > 0:
low = guess + 1
else:
high = guess - 1
makeAguess( counter + 1 )
makeAguess( 0 )
A binary search over 256 values is granted to find the key in 8 turns, but since the liar can lie 8 times I need to run at most 9 searches to find the key, so the game should end after at most 8 * 9 = 72 guesses.
However I keep getting:
RecursionError error: maximum recursion depth exceeded in comparison
And if I swap the 8
in if (counter % 8) == 0:
with a 9
I get a reasonable:
guessed invalid value: -1
The algorithm seems correct and since that's my very first Python code, I think there is something wrong in how I am using the language.
Anyone can spot the bug?
EDIT:
You can run the game by doing
git clone https://github.com/Artemis21/guessers-and-liars
cd guessers-and-liars/guessers
nano Create theGuesser.py
then pasting my code into the nano editor and saving the file.
Finally run
python main.py -r 1
from the guessers-and-liars directory and wait for the response.