Skip to content

Instantly share code, notes, and snippets.

@lnsp
Created March 14, 2016 21:16
Show Gist options
  • Save lnsp/4ca1a93488d84e820e55 to your computer and use it in GitHub Desktop.
Save lnsp/4ca1a93488d84e820e55 to your computer and use it in GitHub Desktop.
from operator import itemgetter
def limit_search_space(space, pattern, bad_char):
# _ for unknown character
index = 0
# filter by symbols
for char in pattern:
if char != '_':
space = [word for word in space if word[index] == char]
else:
space = [word for word in space if word[index] != bad_char]
index += 1
return space
def get_occurrences(space):
occ = dict()
for word in space:
for char in word:
if char in occ:
occ[char] += 1
else:
occ[char] = 1
return sorted(occ.items(), key=itemgetter(1), reverse=True)
# Get word length and dictionary
word_length = int(input("Which length has your word? "))
dictionary = open("/usr/share/dict/words")
# create search space with common length
search_space = set([word.strip().lower() for word in dictionary if not word.strip().endswith("'s") and len(word.strip()) == word_length])
dictionary.close()
# create word pattern
pattern = ['_' for i in range(word_length)]
bad_character = None # character which is banned for the next iteration
guessed_characters = set() # solved characters
while len(search_space) > 1:
#print("Guessed characters:", guessed_characters)
possible_guesses = get_occurrences(search_space)
first_guess = None
# Search for possible guess
for guess in possible_guesses:
if guess[0] not in guessed_characters:
first_guess = guess[0]
break
# Print guess
print("Guessing", first_guess)
guessed_characters.add(first_guess)
solved_pots = input("Solved pots: ").split(",")
for pot in solved_pots:
p = int(pot)
if p == -1:
bad_character = first_guess
break
pattern[p] = first_guess
print("New guessing pattern", pattern)
# Limit and create new search space
search_space = limit_search_space(search_space, pattern, bad_character)
if len(search_space) == 1:
print("Your word is", search_space[0])
else:
print("I don't know your word.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment