1

I am trying to create a program that will guess the number you entered. I was trying to get the computer to get the number in as few guesses as possible so I am doing something like a binary search. I keep getting a Index out of range when I run the code and it gets to total = total[the_low_one:computer2_guess]. I am confused why it is out of range. Should I be adding or subtracting one to the_low_one each time it hits a new low so it stays in range? I would appreciate any help as I am lost. Thanks a bunch in advance! Code:

def second_computer():
    global computer2_score
    computer2_score=0
    computer2_guess= -1
    the_low_one=1
    the_high_one=1000000
    total= range(1,1000000)
    while computer2_guess != pick_number:
        computer2_guess=random.choice(total)
        if computer2_guess>pick_number:
            total=total[the_low_one:computer2_guess]
            the_high_one=computer2_guess-1
        else:
            total=total[computer2_guess:the_high_one]
            the_low_one=computer2_guess+1
        computer2_score+=1
GLHF
  • 3,835
  • 10
  • 38
  • 83
user3818089
  • 345
  • 1
  • 2
  • 19

1 Answers1

1

As total shrinks, the numerical values in the list no longer line up with their indices. You could make it work by doing

total=total[total.index(the_low_one):total.index(the_high_one)]

A simpler approach would be to do away with total altogether and set computer2_guess=random.randint(the_low_one,the_high_one)

Gall
  • 38
  • 4