Check Letters With Sets
00:00 Check Letters With Sets. So far, you’ve only told the user whether they’ve guessed the entire word correctly or not. To give some hints to allow them to deduce the secret word, you’ll add feedback about the individual letters they guess.
00:15 You’ll classify each letter as belonging to one of three categories seen on-screen. A correct letter appears in the same position in the guess as in the secret word, a misplaced letter appears in the secret word but in a different position, and a wrong letter doesn’t appear in the secret word at all.
00:34 On-screen, you can see some guesses classified when the secret word is SNAKE. But how can you find out which letters belong in each category? You’d start by figuring out which letters are correctly placed.
You can quickly use unions, intersections, and differences between two sets to find elements that appear in at least one set, both sets, or only one of the sets. For example, if you have two strings, then you can use set intersection (
&) to find all the letters that appear in both.
R are the letters in
CRANE that don’t appear in
SNAKE. Note that the intersection (
&), union (
|), and difference (
-) operators in sets are used to implement set-theoretic operations in Python, and these are different from Boolean logic operators, such as
not. It’s time to use sets to improve the game.
However, before you start the implementation, you’ll make one other change. Currently, you’ve hard-coded the secret word into the
if test. You’ll use that word when you classify letters, so instead you’ll refer to it using a constant.
WORD constant makes it easier to change the secret word. In the next section, you’ll add a word list that you’ll choose the word from, making the game more interesting. Using what you’ve explored previously about sets, you can now calculate and display the correct, misplaced, and wrong letters.
03:58 You use the set comprehension to find all the correctly placed letters. The misplaced letters are the ones that are in both the guess and the secret word but aren’t correctly placed. Finally, the letters in the guess that aren’t in the secret word at all are categorized as wrong.
04:51 While the information is there, it’s not so easy to understand. Later on in the course, you’ll improve the user interface and make the game both nicer to look at and nicer to play. But before that, you need to improve the game’s variety by creating a word list.
Become a Member to join the conversation.