Using Python to Solve Wordle

use python to solve wordle
Wordle is a fun puzzle to solve. It’s a word square where you have to fill in the crossword-like grid with words that fit into it. The best way to start is by looking at the grid, thinking about what letters are already there, and finding words that match those letters. You’ll find that some of the spaces have more than one letter in them, which means more than one word can fit in those spaces.

Solving Wordle with Python

Building a simple game in Python is easy, but one thing that’s not so simple is keeping track of the guesses you have made and the words you have not guessed.

The first step is setting up a custom class that keeps track of the state of a game. The class will also manage the user input and help validate user input to ensure the game plays correctly.

You need to create a custom class containing the game board and rules. That will require four functions:

  1. The first function checks if you have guessed the secret word or used all six guesses. If so, then it’s game over, and you’ll receive a prompt to restart.
  2. The second function determines the game’s outcome based on what happened and returns a tuple with two elements: a binary representing “win” or “lose.”
  3. The third function saves the latest guess made by a player on the game board and then returns it to display it on screen for others to see.

Building The Game Assistant

We’re going to create a tool that will help you win at the Wordle game, and it’s going to be so easy. We will do this by taking advantage of how the game works and shrinking our search space until you only have a handful of words.

The first thing you need is a word bank—a list of every possible word in the game. Unfortunately, this is much larger than we can handle: there are more than 15,000 words! That means that if you pick randomly, your probability of winning is very low, less than zero! We need to shrink that number down if we want any chance of winning.

Logic

If you want to increase your odds of success, you need to shrink your search space—that is, reduce the number of possible words in the dictionary so that there are fewer possibilities to consider when trying to guess the secret word. You can do this by exploiting the game’s rules and making educated guesses about what letters are in your hidden words based on their position.

First, use colors returned by guesses as a filter: if a letter isn’t green (for example), filter them out from the word bank because they are not in your secret word.

Second, filter all green letters from their predicted position because they may be part of your secret word!

This gives a much smaller search space that is much more manageable.

Since you have already reduced the search space, the only thing left to do is to figure out how to choose the most important words.

You first need to define a function that will return a score for a specific word. It considers the word’s frequency in the source text and its position in the wordle. Script.

To calculate the score, we take into account three critical factors:

Now that you have a function that scores each word based on its position and frequency, you can list and sort them by score so that the highest-scoring words come at the top.

The next step is figuring out which words have vowels and which don’t. This is important because vowels are worth more points than consonants when scoring your guesses.

You can do this by getting rid of all the words that don’t have vowels (this will save you time later on) and then adding back in some bias so that vowels are even more likely than before to be guessed.

Example

First, let us re-create the Wordle game.

Create a new text file and call it “wordle.game.py.” The text file will contain our python code.

For this, we will need two Python modules: turtle and random. Both are built-in modules in Python 3.9

Then we will use the same word list that New York Times uses. This word list has 2309 words.

You can extract the word list from their website:

https://www.nytimes.com/games/wordle/index.html and

https://www.nytimes.com/games/wordle/main.9622bc55.js, as shown in the screenshot below.

Next, we save it in a text file and name it “nytimes_words.txt.”

The next batch of codes shows how to load the words from the text file to a Python List.

				
					# Populate word list from NY Times' wordle lists' file
word_list = []
try:
    with open('nytimes_words.txt') as f:
        for line in f:
            word_list.append(line.strip())
           
except FileNotFoundError:
    print("File not found")
				
			
Next, we will select a random word and use it as our game’s answer.
				
					answer  = random.choice(word_list)

				
			
Next, we will initialize the game with a GUI.
				
					turtle.penup()
turtle.goto(-250,275)
turtle.write("Welcome to the 5 letter word game. \nThe answer is a random 5 letter word. \nYou have 6 tries to guess the word.\n\n",font=("Arial",20,"normal"))
turtle.hideturtle()
turtle.speed(110)

				
			

Next, we will define three functions.

The first one is called draw_square: this function is responsible for drawing a square on the canvas. It takes in x and y coordinates which will be used in moving the canvas pen. It also takes in a color argument for filling in the square.

The second one is called input_guess: this one is responsible for prompting the user for input.

The third one is called check_guess: this one is responsible for comparing the user’s input against the correct answer.

				
					 
def draw_square(x,y,col):
    turtle.penup()
    turtle.goto(x,y)
    turtle.pendown()
 
    turtle.fillcolor(col)
    turtle.begin_fill()
 
    for i in range(4):
        turtle.forward(50)
        turtle.right(90)
 
    turtle.end_fill()
 
def input_guess(prompt):
    my_input = turtle.textinput("5 letter word", prompt).lower()
    if my_input == None : return "     "
    elif len(my_input) != 5: return my_input[0:5]
    else: return my_input.lower()
 
def check_guess(my_input, answer,y):
    count = 0
 
    x = -250
    for i in my_input:
        if i == answer[count]: draw_square(x,y,'green')
        elif i in answer: draw_square(x,y,'yellow')
        else: draw_square(x,y,'red')
        x += 75
        count += 1
   
    turtle.penup()
    turtle.goto(x,y-25)
 
    turtle.write(my_input,font=("Arial",16,"normal"))
 

				
			

Next, we will initialize the y coordinate as 250.
Since our Wordle gives a player six chances, we will create a loop that executes code inside it six times.

If the loop ends before the player has figured out the correct answer, we will let them know they are a loser. We will also display the right answer.

If the player figures out the answer before the end of the loop, we will let them know that they are a winner.

				
					 
y = 250
 
for i in range(6):
    guess_prompt = "Guess the word: "+str(i+1) + "?"
    my_input = input_guess(guess_prompt)
    check_guess(my_input,answer,y)
    y -= 75
 
    if my_input == answer:
        turtle.penup()
        turtle.goto(-300,-200)
        turtle.write("You win!",font=("Arial",20,"normal"))
        break
 
else:
    turtle.penup()
    turtle.goto(-300,-250)
    turtle.write("\nYou lose! The answer was:"+answer,font=("Arial",20,"normal"))
 
turtle.done()


				
			

Now let us run the code.

Please note that the text files “nytimes_words.txt” and “wordle.game.py” must be in the same directory. Also, make sure that you have Python 3.9 installed on your computer

To run this code, open the terminal and run the below command:

				
					py wordle.game.py
				
			

If you did everything right, you should see the game as shown in the screenshot below:

 

wordle and python
Putting It All Together

You’ve now got all the information necessary to create a super-easy tool for winning at wordle. Remember that you will have six guesses when you’re on the actual game, so if you’re short in vowels and a few consonants, remember to use your spare guesses! Check out our Data Science instructor-led courses today to get deeper and get hands-on expertise in Python and Data Science.

Sign Up for Email Updates
Pierian Training
Pierian Training

You May Also Like

Data Science, Tutorials

Analyzing Senate Stock Trades

Analyzing Stock Market Activity of US Senators with Python¶ In 2012, a law called ” Stop Trading on Congressional Knowledge (STOCK) Act of 2012″ was passed, which prohibits the use of non-public information for private profit, including insider trading by members of Congress and other government employees. This law however did not completely ban stock, […]

Data Science, Tutorials

Visualizing Prediction Markets with Kalshi and Python

Visualizing Prediction Markets with Python and Kalshi¶ In this blog post we’ll explore Prediction Markets using Kalshi. What is Kalshi?¶ Kalshi is a predictions market, regulated by the Commodity Futures Trading Commission (CFTC) where you can buy event contracts based on future outcomes for certain events, such as the number of COVID cases in the […]

Python Basics, Tutorials

How to Convert A .py Script into A .exe File

Picture this: you’ve just finished creating a fantastic Python program and intend to let the world see it. You then send your friend a directory containing all your scripts and encourage them to try it out. Only first, they must install Python and then run the program via the IDLE shell or the command line. […]