Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Last active February 15, 2022 03:39
Show Gist options
  • Save shiracamus/388ecf09073f55b237558bc560902e7e to your computer and use it in GitHub Desktop.
Save shiracamus/388ecf09073f55b237558bc560902e7e to your computer and use it in GitHub Desktop.
import wordlist
from typing import Callable
def best_candidate(words: list[str]) -> str:
if len(words) > 3**5:
return None
for candidate in words:
patterns = set("".join("g" if c == w else "y" if c in word else "w"
for c, w in zip(candidate, word))
for word in words)
if len(patterns) == len(words):
return candidate
return None
def scoring(words: list[str]) -> Callable[[str], int]:
count = {letter: 0 for letter in "abcdefghijklmnopqrstuvwxyz"}
for word in words:
for letter in set(word):
count[letter] += 1
def score(word: str) -> int:
return sum(count[letter] for letter in set(word))
return score
def candidate(words: list[str], input_word: str, colors: str) -> list[str]:
def is_candidate(word: str) -> bool:
for i, color in enumerate(colors):
if color == "g" and input_word[i] != word[i]:
return False
if color == "y" and input_word[i] not in word:
return False
if color == "y" and input_word[i] == word[i]:
return False
if color == "w" and input_word[i] in word:
return False
return True
return [word for word in words if is_candidate(word)]
def solve_wordle() -> str:
words = wordlist.word_list
for i in range(6):
print("残り候補数:", len(words))
input_word = best_candidate(words) or max(words, key=scoring(words))
print("入力単語:", input_word)
colors = input("フィードバック色パターン(無:w, 緑:g, 黄:y) ? ")
words = candidate(words, input_word, colors)
if len(words) == 1:
return f"正解は: {words[0]}"
return "ごめんなさい 解けませんでした"
if __name__ == "__main__":
print(solve_wordle())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment