Search code examples
pythonbinary-search

how do I do a binary selection in a loop with python


just a heads up I'm a beginner so the answer is probably pretty easy.

so I'm trying to make a number guessing game where you think of a number between 1 and 100 and then the computer asks you if its x number and you say its either too high or to low

the problem I'm having is after you tell it its too high or too low it just guesses 50 over and over again I've been googling for about 2 hours and I cant figure out why its doing it

   hi = 100
    low = 1
    mid = (hi+low)// 2
    print ("Ok think of a number between 1 and 100.")
    print ("I guess")
    print (mid)
    print ("1.) Too High")
    print ("2.) Too Low")
    g2 = input ("3.) Correct")
    g2 = int(g2)
    hi = int(100)
    low = int(1)
    mid = (hi+low)// 2
while g2 != 3:
    
    if g2 == 1:
        (hi) = (mid) - 1
        print ("I guess")
        print (mid)
        print ("1.) Too High")
        print ("2.) Too Low")
        g2 = input ("3.) Correct")
        g2 = int(g2)
    elif g2 == 2:
        (low) = (mid) + 1
        print ("I guess")
        print (mid)
        print ("1.) Too High")
        print ("2.) Too Low")
        g2 = input ("3.) Correct")
        g2 = int(g2) 

Solution

  • You haven't changed the value of mid in your if statements. You are changing the value of high and low but you are not calculating new mid from it, so it always stays 50. You just you have to add mid = (low + hi) // 2 after calculating new high or low in your if statement.