Skip to content

Instantly share code, notes, and snippets.

@mbollmann
Last active March 26, 2022 20:32
Show Gist options
  • Save mbollmann/96700263ba3d510bb0465a7aac59f9ca to your computer and use it in GitHub Desktop.
Save mbollmann/96700263ba3d510bb0465a7aac59f9ca to your computer and use it in GitHub Desktop.
Finding statistically best guesses for the Wordle game
#!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2021 Marcel Bollmann
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Usage: best_wordle_guess.py WORDLIST [options]
Finds the statistically best guesses for the Wordle game
<https://www.powerlanguage.co.uk/wordle/>, using a list of English words and a
simple frequency-counting approach *by position within the word.*
Arguments:
WORDLIST Lexicon file with one word per line.
Options:
--after GUESS Find a word that has no letters in common with GUESS.
-h, --help Display this helpful text.
"""
from collections import Counter
from docopt import docopt
import itertools as it
import os
from rich.console import Console
from rich.table import Table
console = Console()
def load_wordlist(filename):
wordlist = []
with open(filename, "r") as f:
for line in f:
word = line.strip()
if len(word) != 5:
continue
wordlist.append(word)
wordlist = set(wordlist)
console.print(f"Found {len(wordlist)} words of length 5.")
return wordlist
def find_common_letters(wordlist, MAX=5):
letters = [None] * 5
for pos in range(5):
c = Counter(word[pos] for word in wordlist)
letters[pos] = c.most_common(MAX)
table = Table(title="Most frequent letters by position")
for pos in range(5):
table.add_column(f"Pos {pos+1}", justify="right")
table.add_column(f"Freq", justify="right")
for rank in range(MAX):
row = []
for pos in range(5):
row.extend(str(x) for x in letters[pos][rank])
table.add_row(*row)
console.print("")
console.print(table)
return letters
def find_best_guess(wordlist, letters, after=None):
if after is None:
console.print(f"\n[bold blue]Best initial guesses:[/]")
else:
console.print(f"\n[bold blue]Best guesses after '[green]{after}[/]':[/]")
guesses = Counter()
for candidate in it.product(*letters):
word = "".join([c[0] for c in candidate])
if len(set(word)) != 5:
# contains the same letter more than once
continue
if word not in wordlist:
# not a legal word
continue
if after is not None and len(set(word + after)) < len(word + after):
continue
# sum up the frequencies so we can later sort by best accumulated frequency
guesses[word] = sum(c[1] for c in candidate)
for (word, score) in guesses.most_common(10):
console.print(f"{word} {score:6d}")
if __name__ == "__main__":
args = docopt(__doc__)
wordlist = args["WORDLIST"]
if not os.path.exists(wordlist):
raise FileNotFoundError(f"File not found: {wordlist}")
wordlist = load_wordlist(wordlist)
letters = find_common_letters(wordlist, MAX=10)
find_best_guess(wordlist, letters, after=args["--after"])
@mbollmann
Copy link
Author

Requirements: docopt and rich.

Using words-alpha.txt from dwyl/english-words as the word list, the best valid* guesses that have no letters in common are:

  1. cares
  2. monty
  3. build

(*the Wordle lexicon appears to be much more restrictive than the linked word list)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment