Files
wordle/solver.py
T
2024-03-07 09:46:05 -06:00

107 lines
2.9 KiB
Python

#!/usr/bin/python
import string
from collections import defaultdict
import constraints
import dictionary
import game
class SimilaritySolver(object):
@staticmethod
def _analyze_dictionary(words):
# Word Position, Letter: Count
position_matches = [
defaultdict(int),
defaultdict(int),
defaultdict(int),
defaultdict(int),
defaultdict(int),
]
# Letter: Count
word_matches = defaultdict(int)
for word in words:
unique_letters = set(word)
for letter in unique_letters:
word_matches[letter] += 1
for index in range(len(word)):
letter = word[index]
assert letter in string.ascii_lowercase
position_matches[index][letter] += 1
return position_matches, word_matches
@staticmethod
def _score_word(position_matches, word_matches, word):
result = 0
# Green Score
for index in range(len(word)):
letter = word[index]
green_score = position_matches[index][letter]
result += 10 * green_score
# Yellow Score
for letter in set(word):
yellow_score = word_matches[letter]
result += yellow_score
return result
def scored_words(self, wordle_dictionary=dictionary.words()):
# word: score
scored_words = dict()
position_matches, word_matches = self._analyze_dictionary(wordle_dictionary)
for word in wordle_dictionary:
scored_words[word] = self._score_word(position_matches, word_matches, word)
# Return as list of (word, score) sorted by high-score, word.
result = sorted(scored_words.items(), key=lambda kv: kv[0])
result = sorted(result, key=lambda kv: kv[1], reverse=True)
return result
class LimitsSolver(object):
def scored_words(self, words=dictionary.words()):
# word: score
scored_words = dict()
for word in words:
reduced = const.filter_words(words)
# Our score is how many words did we remove from consideration.
score = len(words) - len(reduced)
scored_words[word] = score
# Return as list of (word, score) sorted by high-score, word.
result = sorted(scored_words.items(), key=lambda kv: kv[0])
result = sorted(result, key=lambda kv: kv[1], reverse=True)
return result
if __name__ == "__main__":
solve = SimilaritySolver()
consts = constraints.Constraints()
consts.update_graded(
"cares",
[
game.LetterResult.INCORRECT,
game.LetterResult.INCORRECT,
game.LetterResult.INCORRECT,
game.LetterResult.INCORRECT,
game.LetterResult.INCORRECT,
],
)
valid_words = consts.filter_words(dictionary.words())
print("Top: ", solve.scored_words(valid_words)[:5])