Consider a string that contains all of the 26 letters of the alphabet just once, for example

jfbqpwcvuamozhilgrxtkndesy

This permutation can be used as the key in a substitution cipher, which in case of the above example maps the letter a onto the letter j, the letter b on the letter f, and so on. This key therefore encrypts the word bakery as fjmprs. Notice that the letters of the encrypted word fjmprs are in alphabetic order. The challenge is to find the permutation of letters of the alphabet, that for a given word list maximizes the number of words that are encrypted as words having their letters in alphabetic order.

Assignment

Your task is to write a program that can be used to determine the score of the above optimization problem for a given key and a given list of words. The score is computed as the number of words in the given list that is encrypted as words having their letters in alphabetic order. In order to do so, you have to implement the following functions:

Example

In the following interactive session we assume the current directory to contain the text file six-letter-words.txt1.

>>> validKey('jfbqpwcvuamozhilgrxtkndesy')
True
>>> validKey('jfbqpwcxvuamozhilgrxtkndesy')
False
>>> validKey('jfbqpwvuamozhilgrxtkndesy')
False
>>> validKey('jfbqpwxvuamozhilgrxtkndesy')
False

>>> encode('bakery', 'jfbqpwcvuamozhilgrxtkndesy')
'fjmprs'
>>> encode('butchery', 'jfbqpwcvuamozhilgrxtkndesy')
'fktbvprs'
>>> encode('bullet', 'jfbqpwcvuamozhilgrxtkndesy')
'fkoopt'
>>> encode('bakery', 'jfbqpwxvuamozhilgrxtkndesy')
Traceback (most recent call last):
AssertionError: invalid key

>>> hasAlphabeticOrder('bakery')
False
>>> hasAlphabeticOrder('fjmprs')
True
>>> hasAlphabeticOrder('bullet')
False
>>> hasAlphabeticOrder('fkoopt')
True

>>> score('jfbqpwcvuamozhilgrxtkndesy', 'six-letter-words.txt')
60
>>> score('idsxvaqtobuefpgcjwzrkmhnyl', 'six-letter-words.txt')
474