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

前端 未结 3 1602
长情又很酷
长情又很酷 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.

    0 讨论(0)
  • 2021-01-22 01:17
    from random import randint
    
    print('choose a number in your brain and if guess is true enter y else any key choose time of guess: ')
    
    print("define the range (A,B) :")
    A = int(input("A: "))
    B = int(input("B: "))
    time = int(input("time:"))
    
    while time != 0:
        ran = randint(A, B)
        inp = input(f"is this {ran} ?")
        time -= 1
        if inp == "y":
            print("bla bla bla python wins!")
            break
        print("NOPE!")
        if time == 0:
            print("computer game over!")
            break
    
    0 讨论(0)
  • 2021-01-22 01:21

    Your logic is backwards. You want to lower the max when you guess too high and raise the min when you guess too low. Try this:

    if guess == number:
        print("The number has been found in ",total," guesses!")
        guessed = 1
    elif guess > number:
        max = guess - 1
    elif guess < number:
        min = guess + 1
    
    0 讨论(0)
提交回复
热议问题