Why does my bisectional approach fail for certain secret words in hangman?

60 Views Asked by At

I've recently started learning Python through an intro online class. The instructor just introduced bisection algorithms, and I'm trying to apply it to a game of hangman. However, my code gets caught in a never ending loop for certain 'secret words', but not for others. For example, it can guess the word "wife", but not "wifey". However, it can guess the word "y". I'm sure I'm missing something obvious, but can't figure it out. (As an aside, I do realize this code won't work for the letter 'z', but that is a separate problem.)

secret_word = 'wifey'
num_guesses = 0
alphabet = "abcdefghijklmnopqrstuvwxyz"
guessed_word = ''
low = 0
high = len(alphabet)+2

while len(guessed_word) != len(secret_word):
    for i in range(len(secret_word)):
        guess_index = 0
        while alphabet[guess_index] != secret_word[i]:
            if ord(alphabet[guess_index]) < ord(secret_word[i]):
                low = guess_index
            else: high = guess_index
            num_guesses += 1
            guess_index = int((high + low)/2)
        else: guessed_word += alphabet[guess_index]
print('num_guesses =', num_guesses)
print(guessed_word)
0

There are 0 best solutions below