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
8
  • Your formatting needs a bit work -- but I think your problem is you initialize the_low_one to 1 instead of 0. Commented Dec 24, 2014 at 0:50
  • What do you mean by formatting? . Commented Dec 24, 2014 at 0:53
  • Your indentation after the while statement needs to be fixed Commented Dec 24, 2014 at 0:54
  • Oh, sorry I didn't realize it didn't indent properly online. Thanks for noticing! I tried changing it to 0 but the same error happened. Commented Dec 24, 2014 at 0:55
  • You have a number of logic errors. Your slices are using values from the total[] array, rather than indicies. And where is pick_number defined? Commented Dec 24, 2014 at 1:00

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

I don't know why I didn't just do the randintin the first place. Thanks!
what happens if randint is 1000000?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.