labyrinth-cs-proj/wordle/solver.py

55 lines
1.5 KiB
Python
Raw Normal View History

2022-11-25 20:24:29 +00:00
words = open("words.txt").read().split("\n")
2022-11-30 12:57:18 +00:00
2022-11-25 20:24:29 +00:00
def partition(word, words):
# Get how many words will remain for each possible response
partitions = []
for a in "MCW":
for b in "MCW":
for c in "MCW":
for d in "MCW":
for e in "MCW":
2022-11-30 12:57:18 +00:00
partitions.append(len(reduce(word, a + b + c + d + e, words)))
2022-11-25 20:24:29 +00:00
return partitions
2022-11-30 12:57:18 +00:00
2022-11-25 20:24:29 +00:00
def reduce(word, result, words):
# word: 5-letter word (lowercase)
# result: 5-letter str consisting of M, C, W (misplaced, correct, wrong)
res = words[:]
for i, s in enumerate(result):
nres = []
for w in res:
if s == "M":
2022-11-30 12:57:18 +00:00
if w[i] != word[i] and word[i] in w:
nres.append(w)
2022-11-25 20:24:29 +00:00
if s == "C":
2022-11-30 12:57:18 +00:00
if w[i] == word[i]:
nres.append(w)
2022-11-25 20:24:29 +00:00
if s == "W":
if w[i] != word[i]:
2022-11-30 12:57:18 +00:00
if not (word[i] in w) or word.count(word[i]) > 1:
2022-11-25 20:24:29 +00:00
nres.append(w)
res = nres
return res
2022-11-30 12:57:18 +00:00
2022-11-25 20:24:29 +00:00
print("WORDLE SOLVER")
print("=============")
# First guess is precomputed
opt = "crate"
result = ""
while result != "CCCCC":
print(opt)
result = input("> ").upper()
words = reduce(opt, result, words)
opt = ""
opt_size = float("inf")
for word in words:
p = partition(word, words)
2022-11-30 12:57:18 +00:00
avg_partition_size = sum(p) / len(p)
2022-11-25 20:24:29 +00:00
if opt_size > avg_partition_size:
opt_size = avg_partition_size
opt = word
2022-11-30 12:57:18 +00:00
# print(p)