Created
November 10, 2015 20:43
-
-
Save galvez/ff6940fb202bf039cf08 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
#!/usr/bin/env python | |
from re import sub | |
from string import ascii_lowercase | |
from code import interact | |
from collections import defaultdict | |
from random import choice, shuffle | |
from itertools import groupby | |
VOWELS = list('aeiou') | |
CONSONANTS = list(sub('[aeiou]', '', ascii_lowercase)) | |
WORD_FILE = "/usr/share/dict/words" | |
WORD_HASH = {} | |
WORD_LIST = [] | |
WORD_TREE = {} | |
def load_words(): | |
with open(WORD_FILE) as words_file: | |
for word in words_file.xreadlines(): | |
parsed_word = word.strip().lower() | |
WORD_LIST.append(parsed_word) | |
WORD_HASH[parsed_word] = 1 | |
w_len = len(parsed_word) | |
if w_len not in WORD_TREE: | |
WORD_TREE[w_len] = [parsed_word] | |
else: | |
WORD_TREE[w_len].append(parsed_word) | |
def _shuffle_word(word): | |
letters = list(word) | |
new_word = [] | |
for l in letters: | |
if l in CONSONANTS: | |
CONSONANTS.remove(l) | |
nl = choice(CONSONANTS) | |
new_word.append(nl) | |
CONSONANTS.append(l) | |
elif l in VOWELS: | |
VOWELS.remove(l) | |
nl = choice(VOWELS) | |
new_word.append(nl) | |
VOWELS.append(l) | |
new_word = ''.join(new_word) | |
while new_word in WORD_HASH: | |
new_word = _shuffle_word(word) | |
return new_word | |
def generate_puzzle(difficulty=3): | |
if difficulty == -1: # unsolvable | |
word = choice(WORD_TREE[choice(range(5, 10))]) | |
word = _shuffle_word(word) | |
elif difficulty in WORD_TREE: | |
word = choice(WORD_TREE[difficulty]) | |
else: | |
return None | |
s_word = list(word) | |
shuffle(s_word) | |
s_word = ''.join(s_word) | |
while WORD_HASH.get(s_word): | |
s_word = list(word) | |
shuffle(s_word) | |
s_word = ''.join(s_word) | |
return word, s_word | |
def check_answer(answer, puzzle): | |
answer_sorted = sorted(answer) | |
puzzle_sorted = sorted(puzzle) | |
if answer_sorted != puzzle_sorted: | |
return False | |
if answer not in WORD_HASH: | |
return False | |
return True | |
if __name__ == "__main__": | |
load_words() | |
orig, puzzle = generate_puzzle(-1) | |
print orig | |
print puzzle | |
answer = raw_input() | |
print check_answer(answer, puzzle) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment