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.
Assuming you are trying to implement something similar to wordle, the issue arises from your approach to replacing characters in
word
andguess
lists. You are altering the original lists when you setword[y] = 1
andguess[y] = 0
in the first code block. Consequently, in subsequent iterations, the conditionword.count(character_x) > 0
can fail because1
and0
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 becauseword.index(guess[y])
is trying to find an index for a character that has been replaced with0
, which might not exist inword
anymore. Similarly,ValueError: 0 is not in list
happens when0
(set in previous iterations) is not found inword
.To resolve this, you should avoid altering the original lists
word
andguess
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:matched
, with the same length asword
andguess
, filled withFalse
.matched
asTrue
.word
whose correspondingmatched
value isFalse
.