# Code that solves NY Times Spelling Bee "Hive"
# game with a CS134 twist - only isograms!

#######################################
## HELPER FUNCTIONS FOR FILE READING ##
##  May contain content we haven't   ##
##  covered in class yet!            ##
def read_words(fname):
    '''Reads in a file from fname, returns as a list of strings
    This uses concepts from one of our upcoming classes - no need to understand it.
    '''
    result = []
    # read in from file
    with open(fname ,'r') as f:
        for word in f.readlines():
            result += [lower(word).strip()]
    return result    

def lower(word):
    """ Returns a lowercased version of the word
    >>> lower("HELLO!")
    'hello!'
    """
    result = ''
    for c in word:
        if ord(c) >= ord('A') and ord(c) <= ord('Z'): # if capital letter
            result += chr(ord(c) - (ord('A')-ord('a'))) # lowerify
        else: # otherwise, keep original
            result += c
    return result

#######################################
##     CLASS ACTIVITY BEGINS HERE    ##
def is_isogram(word):
    """ Returns True if word is a string without any repeat letters
    >>> is_isogram("iris")
    False
    >>> is_isogram("lida")
    True
    """
    return len(word) == len(set(word))

def spelling_bee(center, hive, word_list):
    """ Returns list of words that match NYT Spelling Bee - CS134 rules.
    >>> spelling_bee('y', 'ymaiflr', ['airy', 'fairly', 'hello'])
    ['airy', 'fairly']
    """
    matches = []

    for word in word_list:
        # make sure center is in there, word is long enough
        if len(word) > 3 and center in word:
            # make sure only hive letters are in there, and only once
            if not (set(word) - set(hive)) and is_isogram(word):
                    matches += [word]

    return matches

########################################
# only runs when code is run as a script
if __name__ == '__main__': 

    # How many 7 (or less) letter isograms are in the letters below, using the letter 'y'?
    # ['y', 'm', 'a', 'i', 'f', 'l', 'r']
    sb = spelling_bee('y', 'ymaiflr', read_words("/usr/share/dict/words"))
    print(sb)


    