Guessing algorithm does not seem to work, guessing number by Python

前端 未结 3 1641
长情又很酷
长情又很酷 2021-01-22 00:34

I am struggling with some simple algorithm which should make python guess the given number in as few guesses as possible. It seems to be running but it is extremely slow. What a

3条回答
  •  庸人自扰
    2021-01-22 01:17

    Apart from having the logic backwards, you should not be using min and max as variable names. They are python functions. You can also use while True and break as soon as the number is guessed.

    while True:
        guess = (mn + mx) // 2
        total += 1
        if guess == number:
            print("The number has been found in {} guesses!".format(total))
            break
        elif guess < number:
            mn = guess
        elif guess > number:
            mx = guess
    

    You will also see by not adding or subtracting 1 from guess this will find the number in less steps.

提交回复
热议问题