Home > OS >  Why this program crashes on high value, and not on low?
Why this program crashes on high value, and not on low?

Time:09-20

low=1
high=1000
answer=int(input(f"ENTER A NUMBER BETWEEN {low} AND {high}: "))
guess=(high//2)
guesses=1
    
while guess!=answer:
    print(f"CPU guess is {guess}.")
    if guess>answer:
        high=guess
    else:
        low=guess
    guess=((high low)//2)
    guesses =1
else:
    print(f"CPU got it right in {guesses} guesses.")

When I enter 1000 as the answer the code crashes and goes on printing 999 and never stops, it happens just when we enter the high* value as the answer.

CodePudding user response:

Here is a solution that works:

But I hope someone finds a more elegant way

low=1
high=1000
answer=int(input(f"ENTER A NUMBER BETWEEN {low} AND {high}: "))
guess=(high//2)
guesses=1

while guess!=answer:
    print(f"CPU guess is {guess}.")
    if guess>answer:
        high=guess
    else:
        low=guess
    if not (abs(high - guess) <= 1 and abs(low - guess) <= 1):
        guess = round((high low)/2)
    else:
        if  guess < ((high low)/2):
            guess = high
        else: 
            guess = low
        
    guesses =1
print(f"CPU guess is {guess}.")
print(f"CPU got it right in {guesses} guesses.")

CodePudding user response:

Try this loop modification:

if guess > answer:
    high = guess - 1
else:
    low = guess   1

Explanation: if the guess is e.g. 500, and is incorrect (otherwise the while loop would end), you have to exclude that value (500) when narrowing the search interval. In detail, if the correct answer is somewhere below the guess, you don't search up to 500 in the next step, but only up to 499. And similarly the other case, if it is above 500, search from 501.


And if you want a safety net (input not in the allowed range 1-1000), add this:

if high <= low:
    print("NOT FOUND")
    break
  • Related