Data availability

story.txt words.txt

Description

Description — page 1
Description — page 1

Download original PDF: ## Description — page 1

Description — page 2
Description — page 2
Description — page 3
Description — page 3
Description — page 4
Description — page 4
Description — page 5
Description — page 5
Description — page 6
Description — page 6
Description — page 7
Description — page 7
Description — page 8
Description — page 8
Description — page 9
Description — page 9
Description — page 10
Description — page 10

MIT6_0001F16_Pset4.pdf


Part A: Permutation of a string (Write a Recursive function)

‘abc’ → ‘abc’, ‘acb’, ‘bac’, ‘bca’, ‘cab’, ‘cba’

How about abcdefg?

→ Its NOT about change the POSITION of letters → But the INSERTION a → b_c and c_b

My python code

def insert_letter(letter, string_list):
    result = []
    
    for i in range(len(string_list)):
            string_i = string_list[i]
            for i in range(len(string_i)+1):
                new_string = string_i[:i] + letter + string_i[i:]
                result.append(new_string)
                
    return result
 
 
 
 def get_permutations(sequence):

    # determine the base -> only 1 letter left in the sequence    
    if len(sequence) == 1:
        return list(sequence)
    else:
        final_result = insert_letter(sequence[0], get_permutations(sequence[1:]))
        return final_result

(saved as ps4a.py)


Part B: Cipher Like Caesar (Class and Inheritance)

See the description in the above PDF

My pseudo code:

My pseudo code:
My pseudo code:

Download original image: ### My pseudo code:

My python code

# Problem Set 4B
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx

import string

### HELPER CODE ###
def load_words(file_name):
    '''
    file_name (string): the name of the file containing 
    the list of words to load    
    
    Returns: a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    '''
    print("Loading word list from file...")
    # inFile: file
    inFile = open(file_name, 'r')
    # wordlist: list of strings
    wordlist = []
    for line in inFile:
        wordlist.extend([word.lower() for word in line.split(' ')])
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def is_word(word_list, word):
    '''
    Determines if word is a valid word, ignoring
    capitalization and punctuation

    word_list (list): list of words in the dictionary.
    word (string): a possible word.
    
    Returns: True if word is in word_list, False otherwise

    Example:
    >>> is_word(word_list, 'bat') returns
    True
    >>> is_word(word_list, 'asdf') returns
    False
    '''
    word = word.lower()
    word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
    return word in word_list

def get_story_string():
    """
    Returns: a story in encrypted text.
    """
    f = open("story.txt", "r")
    story = str(f.read())
    f.close()
    return story











### END HELPER CODE ###

WORDLIST_FILENAME = 'words.txt'

class Message(object):
    
    def __init__(self, text):
        '''
        Initializes a Message object
                
        text (string): the message's text

        a Message object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''
        
        self.message_text = text # show my input text
        self.valid_words = load_words(WORDLIST_FILENAME) # show all valid words
        
        

    def get_message_text(self):
        '''
        Used to safely access self.message_text outside of the class
        
        Returns: self.message_text
        '''
        return self.message_text


    def get_valid_words(self):
        '''
        Used to safely access a copy of self.valid_words outside of the class.
        This helps you avoid accidentally mutating class attributes.
        
        Returns: a COPY of self.valid_words
        '''
        # copy of list
        copy_valid_words = self.valid_words[:]
        return copy_valid_words


    def build_shift_dict(self, shift):
        '''
        Creates a dictionary that can be used to apply a cipher to a letter.
        The dictionary maps every uppercase and lowercase letter to a
        character shifted down the alphabet by the input shift. The dictionary
        should have 52 keys of all the uppercase letters and all the lowercase
        letters only.        
        
        shift (integer): the amount by which to shift every letter of the 
        alphabet. 0 <= shift < 26

        Returns: a dictionary mapping a letter (string) to 
                 another letter (string). 
        '''
        
        
        # assertion
        assert 0 <= shift < 26, "shift has to be: 0 <= shift < 26" 
        
        # alphabet string
        lowercase = string.ascii_lowercase
        uppercase = string.ascii_uppercase
        
        dict_lower = {}
        for i in range(len(lowercase)):
            if i+shift <= 25:
                dict_lower[lowercase[i]] = lowercase[i+shift]
            elif i+shift > 25:
                dict_lower[lowercase[i]] = lowercase[i+shift-26]
        
        dict_upper = {}
        for i in range(len(uppercase)):
            if i+shift <= 25:
                dict_upper[uppercase[i]] = uppercase[i+shift]
            elif i+shift > 25:
                dict_upper[uppercase[i]] = uppercase[i+shift-26]
        
        dict_final = dict_lower | dict_upper
        return dict_final
        
        

    def apply_shift(self, shift):
        '''
        Applies the Caesar Cipher to self.message_text with the input shift.
        Creates a new string that is self.message_text shifted down the
        alphabet by some number of characters determined by the input shift        
        
        shift (integer): the shift with which to encrypt the message.
        0 <= shift < 26

        Returns: the message text (string) in which every character is shifted
             down the alphabet by the input shift
        '''
        assert 0 <= shift < 26, "shift has to be: 0 <= shift < 26" 
        
        shift_dict = self.build_shift_dict(shift)
        raw_message_text = self.get_message_text()
        new_message_text = ""
        for char in raw_message_text:
            if char in string.ascii_lowercase+string.ascii_uppercase:
                new_message_text = new_message_text + shift_dict[char]
            else:
                new_message_text = new_message_text + char
        
        #return Message(new_message_text)
        return new_message_text
        
        


# Define sub-class

class PlaintextMessage(Message):
    def __init__(self, text, shift):
        '''
        Initializes a PlaintextMessage object        
        
        text (string): the message's text
        shift (integer): the shift associated with this message

        A PlaintextMessage object inherits from Message and has five attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
            self.shift (integer, determined by input shift)
            self.encryption_dict (dictionary, built using shift)
            self.message_text_encrypted (string, created using shift)

        '''
        Message.__init__(self, text) # self.message_text and self.valid_words from parents

        self.shift = shift
        self.encryption_dict = self.build_shift_dict(shift)
        self.message_text_encrypted = self.apply_shift(shift)



    def get_shift(self):
        '''
        Used to safely access self.shift outside of the class
        
        Returns: self.shift
        '''
        
        return self.shift


    def get_encryption_dict(self):
        '''
        Used to safely access a copy self.encryption_dict outside of the class
        
        Returns: a COPY of self.encryption_dict
        '''
        # copy of a dictionary
        copy_encryption_dict = self.encryption_dict.copy()
        return copy_encryption_dict
        
        

    def get_message_text_encrypted(self):
        '''
        Used to safely access self.message_text_encrypted outside of the class
        
        Returns: self.message_text_encrypted
        '''
        
        return self.message_text_encrypted
        
    def change_shift(self, new_shift):
        '''
        Changes self.shift of the PlaintextMessage and updates other 
        attributes determined by shift.        
        
        shift (integer): the new shift that should be associated with this message.
        0 <= shift < 26

        Returns: nothing
        '''
        
        assert 0 <= new_shift < 26, "shift has to be: 0 <= shift < 26" 
        
        # updates other attributes
        self.shift = new_shift
        self.encryption_dict = self.build_shift_dict(new_shift)
        self.message_text_encrypted = self.apply_shift(new_shift)



class CiphertextMessage(Message):
    def __init__(self, text):
        '''
        Initializes a CiphertextMessage object
                
        text (string): the message's text

        a CiphertextMessage object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''
        
        Message.__init__(self, text)


    def decrypt_message(self):
        '''
        Decrypt self.message_text by trying every possible shift value
        and find the "best" one. We will define "best" as the shift that
        creates the maximum number of real words when we use apply_shift(shift)
        on the message text. If s is the original shift value used to encrypt
        the message, then we would expect 26 - s to be the best shift value 
        for decrypting it.

        Note: if multiple shifts are equally good such that they all create 
        the maximum number of valid words, you may choose any of those shifts 
        (and their corresponding decrypted messages) to return

        Returns: a tuple of the best shift value used to decrypt the message
        and the decrypted message text using that shift value
        '''
        
        best_shift_word = {}
        
        for shift_i in range(26):
            words_score = 0
            
            # with each shift value, shift the encrypted message
            decrypt_msg = self.apply_shift(shift_i)
            # split it based on whitespace to create a list of words
            decrypt_msg_word_list = decrypt_msg.split(" ")
            
            # calculate the score of this list of words
            for i in range(len(decrypt_msg_word_list)):
                if is_word(self.get_valid_words(), decrypt_msg_word_list[i]):
                    words_score = words_score + 1
            
            # output a dictionary with {shift value: score}    
            best_shift_word[shift_i] = words_score
        
        # subset the shift value with max(score) in the distionary
        best_shift = max(best_shift_word, key=best_shift_word.get)
        
        # return a tuple (best shift value, decrypted message text)
        final_decrypt_msg = self.apply_shift(best_shift)
        return ((best_shift, final_decrypt_msg))





if __name__ == '__main__':

    #Example test case (PlaintextMessage)
    plaintext = PlaintextMessage('hello', 2)
    print('Expected Output: jgnnq')
    print('Actual Output:', plaintext.get_message_text_encrypted())

    #Example test case (CiphertextMessage)
    ciphertext = CiphertextMessage('jgnnq')
    print('Expected Output:', (24, 'hello'))
    print('Actual Output:', ciphertext.decrypt_message())

    # example: if you type the non-existed word
    story = get_story_string()
    
    ciphertext = CiphertextMessage(story)
    print(ciphertext.decrypt_message())

Part C: Substitution Cipher

See the description in the above PDF

My Python code

import string
from ps4a import get_permutations

### HELPER CODE ###
def load_words(file_name):
    '''
    file_name (string): the name of the file containing 
    the list of words to load    
    
    Returns: a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    '''
    
    print("Loading word list from file...")
    # inFile: file
    inFile = open(file_name, 'r')
    # wordlist: list of strings
    wordlist = []
    for line in inFile:
        wordlist.extend([word.lower() for word in line.split(' ')])
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def is_word(word_list, word):
    '''
    Determines if word is a valid word, ignoring
    capitalization and punctuation

    word_list (list): list of words in the dictionary.
    word (string): a possible word.
    
    Returns: True if word is in word_list, False otherwise

    Example:
    >>> is_word(word_list, 'bat') returns
    True
    >>> is_word(word_list, 'asdf') returns
    False
    '''
    word = word.lower()
    word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
    return word in word_list


### END HELPER CODE ###

WORDLIST_FILENAME = 'words.txt'

# you may find these constants helpful
VOWELS_LOWER = 'aeiou'
VOWELS_UPPER = 'AEIOU'
CONSONANTS_LOWER = 'bcdfghjklmnpqrstvwxyz'
CONSONANTS_UPPER = 'BCDFGHJKLMNPQRSTVWXYZ'

class SubMessage(object):
    def __init__(self, text):
        '''
        Initializes a SubMessage object
                
        text (string): the message's text

        A SubMessage object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''
        self.message_text = text
        self.valid_words = load_words(WORDLIST_FILENAME)

    
    def get_message_text(self):
        '''
        Used to safely access self.message_text outside of the class
        
        Returns: self.message_text
        '''
        return self.message_text

    def get_valid_words(self):
        '''
        Used to safely access a copy of self.valid_words outside of the class.
        This helps you avoid accidentally mutating class attributes.
        
        Returns: a COPY of self.valid_words
        '''
        copy_valid_words = self.valid_words[:]
        return copy_valid_words
                
    def build_transpose_dict(self, vowels_permutation):
        '''
        vowels_permutation (string): a string containing a permutation of vowels (a, e, i, o, u)
        
        Creates a dictionary that can be used to apply a cipher to a letter.
        The dictionary maps every uppercase and lowercase letter to an
        uppercase and lowercase letter, respectively. Vowels are shuffled 
        according to vowels_permutation. The first letter in vowels_permutation 
        corresponds to a, the second to e, and so on in the order a, e, i, o, u.
        The consonants remain the same. The dictionary should have 52 
        keys of all the uppercase letters and all the lowercase letters.

        Example: When input "eaiuo":
        Mapping is a->e, e->a, i->i, o->u, u->o
        and "Hello World!" maps to "Hallu Wurld!"

        Returns: a dictionary mapping a letter (string) to 
                 another letter (string). 
        '''
        transpose_dict = {}
        vowels_permutation = vowels_permutation.lower()
        
        for i in range(len(CONSONANTS_LOWER)):
            transpose_dict[CONSONANTS_LOWER[i]] = CONSONANTS_LOWER[i]
        for i in range(len(CONSONANTS_UPPER)):
            transpose_dict[CONSONANTS_UPPER[i]] = CONSONANTS_UPPER[i]
        
        for i in range(len(VOWELS_LOWER)):
            transpose_dict[VOWELS_LOWER[i]] = vowels_permutation[i]
        for i in range(len(VOWELS_UPPER)):
            transpose_dict[VOWELS_UPPER[i]] = vowels_permutation[i].upper()
        
        return transpose_dict
        
        
        
    def apply_transpose(self, transpose_dict):
        '''
        transpose_dict (dict): a transpose dictionary
        
        Returns: an encrypted version of the message text, based 
        on the dictionary
        '''
        raw_msg = self.get_message_text()
        encrypted_msg = ""
        
        for letter in raw_msg:
            if letter in VOWELS_LOWER+VOWELS_UPPER+CONSONANTS_LOWER+CONSONANTS_UPPER:
                encrypted_msg = encrypted_msg + transpose_dict[letter]
            else:
                encrypted_msg = encrypted_msg + letter
        
        return encrypted_msg





class EncryptedSubMessage(SubMessage):
    def __init__(self, text):
        '''
        Initializes an EncryptedSubMessage object

        text (string): the encrypted message text

        An EncryptedSubMessage object inherits from SubMessage and has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''
        SubMessage.__init__(self, text)
        
        

    def decrypt_message(self):
        '''
        Attempt to decrypt the encrypted message 
        
        Idea is to go through each permutation of the vowels and test it
        on the encrypted message. For each permutation, check how many
        words in the decrypted text are valid English words, and return
        the decrypted message with the most English words.
        
        If no good permutations are found (i.e. no permutations result in 
        at least 1 valid word), return the original string. If there are
        multiple permutations that yield the maximum number of words, return any
        one of them.

        Returns: the best decrypted message    
        
        Hint: use your function from Part 4A
        '''
        
        # obtain a list of vowel permutations, lowercase or uppercase is not important because
        # build_transpose_dict() will firstly convert all to lowercase
        permutation_of_vowels = get_permutations(VOWELS_LOWER)
        
        # for each vowel permutation, perform apply_transpose() function
        final_result = {}
        for i in range(len(permutation_of_vowels)):
            dict_tmp = self.build_transpose_dict(permutation_of_vowels[i])
            transposed_msg = self.apply_transpose(dict_tmp)
            
            # calculate valid word score for each transposed_msg
            score = 0
            for word in transposed_msg.split(" "):
                if is_word(self.get_valid_words(), word):
                    score = score + 1
            # add the results in final dictionary
            final_result[transposed_msg] = score
        
        # return the original text if no good permutations are found         
        if max(final_result.values()) < 1:
            return self.get_message_text()
        else:
            return max(final_result, key=final_result.get)


if __name__ == '__main__':

    # Example test case
    message = SubMessage("Hello World!")
    permutation = "eaiuo"
    enc_dict = message.build_transpose_dict(permutation)
    print("Original message:", message.get_message_text(), "Permutation:", permutation)
    print("Expected encryption:", "Hallu Wurld!")
    print("Actual encryption:", message.apply_transpose(enc_dict))
    enc_message = EncryptedSubMessage(message.apply_transpose(enc_dict))
    print("Decrypted message:", enc_message.decrypt_message())
     
    #TODO: WRITE YOUR TEST CASES HERE

Code availability

ps4a.py ps4b.py ps4c.py

← Back to all posts