Created
June 17, 2019 05:31
-
-
Save dogoyaro/55ee396ab9d2384916f8fcd802fdeebb to your computer and use it in GitHub Desktop.
This is a python script I wrote to beat my friend at the anagram game on Imessage. It uses cool stuff like binary search and finding all substrings given a string
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
import math | |
from itertools import permutations | |
# Find or create a dictionary file that will be cross-referenced to match possible words | |
words = open("/usr/share/dict/web2", 'r').readlines() | |
words = [word.lower() for word in words] | |
def compose(top, val): | |
if (type(val) == str): | |
val = [val] | |
return top + val | |
def find_substrings(letters): | |
if len(letters) == 0: | |
return [] | |
if len(letters) == 1: | |
return [letters] | |
top = [letters[0]] | |
first = [compose(top, val) for val in find_substrings(letters[1:])] | |
second = find_substrings(letters[1:]) | |
return first + second + top | |
def create_anagrams(letters): | |
# generate all possible words of size 3 an above from 6 letters (constraints from the game) | |
# cross reference that against a dictionary | |
substrings = [''.join(val) | |
for val in find_substrings(letters) if len(val) >= 3] | |
words = [] | |
for string in substrings: | |
possible_words = [] | |
possible_words = [''.join(p) for p in permutations(string)] | |
possbile_words = set(possible_words) | |
new_words = [word for word in possible_words if is_word(word)] | |
words += new_words | |
return words | |
def is_word(word): | |
return binary_search(words, word) | |
def compare_words(dictionary_word, word): | |
# readline appends a "\n", too lazy to find a better alternative | |
return dictionary_word[:-1] > word | |
def binary_search(dictionary, word): | |
len_dictionary = len(dictionary) | |
if len_dictionary < 1: | |
return False | |
if len_dictionary == 1: | |
if dictionary[0].find(word) == 0: | |
return True | |
else: | |
return False | |
middle_index = math.floor(len_dictionary/2) | |
left_side = dictionary[0:middle_index] | |
right_side = dictionary[middle_index:] | |
middle_value = dictionary[middle_index] | |
if compare_words(middle_value, word): | |
return binary_search(left_side, word) | |
return binary_search(right_side, word) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Only that you didn't beat your friend. She still whooped your a** even with your fancy script, which only proves one thing, that she is smart as f**k :).
Nice script.