'''
Created on Sep 18, 2013

@author: guestuser
'''
# connect file resource to your program and 
# convert it into a usable list structure
d = open("boggle_dictionary.txt")
words = d.read().split("\n")

# count 5-letter words, accumulation style
count = 0
for w in words:
    if len(w) == 5:
        #print(w)
        count += 1
print(count)

# count 5-letter words, by "counting" in list comprehension
words5 = [ 1 for w in words if len(w) == 5 ]
print(sum(words5))
print(words5[0])
# count 5-letter words, by filtering
words5 = [ w for w in words if len(w) == 5 ]
print(len(words5))
print(words5[0])

# count words that start with 'q'
#   WARNING, some blank lines, so empty words!
wordsQ = [ w for w in words if len(w) != 0 and w[0] == 'q' ]
print(len(wordsQ))

# find longest word, accumulation style
longest = ''
for w in words:
    if len(w) >= len(longest):
        longest = w
print(longest)

# find longest number of letters using list comprehension
longest = max([ len(w) for w in words ])
print(longest)
# find all words whose length is the same as longest
longWords = [ w for w in words if len(w) == longest ]
print(longWords)


qWords = [ w for w in words if w.startswith('q') ]
# sort words, alphabetically
print(sorted(qWords))
print(sorted(qWords, reverse=True))
# sort words, by length
print(sorted(qWords, reverse=True, key=len))

# note, key can refer to any function that takes a string and returns a number
def mylen (w):
    if w.endswith('t'): return 1
    else:               return len(w) 

print(sorted(qWords, key=mylen))
