Why is my code searching for an index that doesn't exist?

117 Views Asked by At

Before explanation, this will make a lot more sense if you've played the online game Wordle, as I am attempting to recreate it with an AI add-on in Python 3.

I have the player input a 5 letter strings that is split into a 5 item list, and a 5 letter string representing the word split into a 5 item list. These are then both duplicated as lists "guessCopy" and "wordCopy" with the lines.

guessCopy = guess[:]
wordCopy = word[:]

to make sure I don't irreversibly mess with the data of the word.

When checking for "yellow" letters in a guess, my program will replace characters that are the same in a word and in a guess with "0" or "1", with these bits of code here:

if guess[y] == word[y]:
    results[y] = "Green"
    word[y] = 1
    guess[y] = 0

and

if word.count(character_x) > 0:
    results[y] = "Yellow"
    word[word.index(guess[y])] = 1
    guess[y] = 0

After each run of the code to get the color results of each letter, I would add the results to a list "results" and then revert the word back to its original status. I do that so next time I run it, I don't get an error trying to search for a "0" or a "1" in the word that isn't there.

It's this line of code: word[word.index(guess[y])] = 1, that's causing me some problems.

This only causes me problems around 2 out of 5 times, but this code is run 6 times over the course of the program and it will almost always crash, every time. It gives me the error message:

IndexError: list index out of range

and, on occasion:

ValueError: 0 is not in list

I didn't recognize either error message, so, of course, I looked them up here. None of the answers seemed to apply to my problem, and the debug does practically nothing. It just seems to randomly break and I don't know why, but it happens too frequently to be ignored.

1

There are 1 best solutions below

1
On

Assuming you are trying to implement something similar to wordle, the issue arises from your approach to replacing characters in word and guess lists. You are altering the original lists when you set word[y] = 1 and guess[y] = 0 in the first code block. Consequently, in subsequent iterations, the condition word.count(character_x) > 0 can fail because 1 and 0 are invalid characters in the original word (assuming like worldle the word only contain English alphabet letters )

The IndexError: list index out of range occurs because word.index(guess[y]) is trying to find an index for a character that has been replaced with 0, which might not exist in word anymore. Similarly, ValueError: 0 is not in list happens when 0 (set in previous iterations) is not found in word.

To resolve this, you should avoid altering the original lists word and guess directly. Instead, use a separate list to keep track of the positions matched (green) or found elsewhere in the word (yellow). Try something like this:

  1. Initialize a new list, say matched, with the same length as word and guess, filled with False.
  2. First, mark all green positions (exact matches) in matched as True.
  3. Then, for yellow checks, only consider characters in word whose corresponding matched value is False.
matched = [False] * len(word)  # Initialize matched list

# Check for green letters
for y in range(len(guess)):
    if guess[y] == word[y]:
        results[y] = "Green"
        matched[y] = True

# Check for yellow letters
for y in range(len(guess)):
    if not matched[y] and guess[y] in word:
        # Find the first unmatched occurrence in word
        for w in range(len(word)):
            if word[w] == guess[y] and not matched[w]:
                results[y] = "Yellow"
                matched[w] = True
                break