Last active
July 24, 2020 10:56
-
-
Save lukesalamone/a815cda5e427b28db78e0caafdbbc0f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def buildRegex(secret, knownLetters): | |
regex = '' | |
for letter in secret: | |
if letter in knownLetters: | |
regex += letter | |
else: | |
regex += '.' | |
return regex | |
# "secret" is the secret word | |
# "dictionary" is the list of available words | |
def playGame(secret, dictionary): | |
if secret not in dictionary: | |
print('secret not in dictionary') | |
return 0 | |
dictionary = list(filter(lambda x: len(x) == len(secret), dictionary)) | |
mistakes = 0 | |
alphabet = list('abcdefghijklmnopqrstuvwxyz') | |
knownLetters = set() | |
regex = buildRegex(secret, knownLetters) | |
while True: | |
# build probabilities | |
probabilities = dict.fromkeys(alphabet, 0) | |
for word in dictionary: | |
# iterate over letters left in alphabet which are in word | |
for letter in alphabet: | |
if letter in word: | |
probabilities[letter] += 1 | |
# find letter with highest probability | |
maxProb = 0 | |
guess = 'z' | |
for letter in probabilities: | |
if probabilities[letter] > maxProb: | |
maxProb = probabilities[letter] | |
guess = letter | |
alphabet = list(filter(lambda x: x != guess)) | |
# guess the letter | |
if guess in secret: | |
knownLetters.add(guess) | |
regex = buildRegex(secret, knownLetters) | |
if not '.' in regex: | |
return mistakes | |
dictionary = list(filter(lambda x: re.match(regex, x), dictionary)) | |
if len(dictionary) == 1: | |
return mistakes | |
else: | |
mistakes += 1 | |
dictionary = list(filter(lambda x: guess not in word, dictionary)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment