Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
286 changes: 286 additions & 0 deletions exercise/.ipynb_checkpoints/ps4b-checkpoint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,286 @@
# 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
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
'''
return self.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).
'''
lower = string.ascii_lowercase
upper = string.ascii_uppercase
sl = lower[shift:] + lower[:shift]
su = upper[shift:] + upper[:shift]
res = {}
for i in range(26):
res[lower[i]] = sl[i]
res[upper[i]] = su[i]
return res

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
'''
shift_dict = self.build_shift_dict(shift)
encrypted = []

for ch in self.message_text:
if ch in shift_dict:
encrypted.append(shift_dict[ch])
else:
encrypted.append(ch)
return ''.join(encrypted)

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)
'''
super().__init__(text)
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
'''
return self.encryption_dict.copy()

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, 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
'''
self.shift = shift
self.encryption_dict = self.build_shift_dict(shift)
self.message_text_encrypted = self.apply_shift(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)
'''
super().__init__(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 = 0
best_count = -1
best_decryption = self.message_text

for shift in range(26):
# apply candidate decoding shift
decrypted_text = self.apply_shift(shift)
words = decrypted_text.split()
count_valid = 0

for w in words:
if is_word(self.valid_words, w):
count_valid += 1

if count_valid > best_count:
best_count = count_valid
best_shift = shift
best_decryption = decrypted_text

return (best_shift, best_decryption)

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())

#TODO: WRITE YOUR TEST CASES HERE

#TODO: best shift value and unencrypted story

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

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

# Your own tests (you can add more)
plaintext2 = PlaintextMessage('This is a test message!', 5)
print('Plaintext2 encrypted:', plaintext2.get_message_text_encrypted())

ciphertext2 = CiphertextMessage(plaintext2.get_message_text_encrypted())
print('Ciphertext2 decrypted:', ciphertext2.decrypt_message())

# Decrypt the story
story_cipher = CiphertextMessage(get_story_string())
best_shift, decrypted_story = story_cipher.decrypt_message()
print('\nBest shift for story:', best_shift)
print('Decrypted story:')
print(decrypted_story)
Binary file added exercise/__pycache__/ps4a.cpython-313.pyc
Binary file not shown.
10 changes: 10 additions & 0 deletions exercise/ps4a.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
def get_permutations(sequence):
if len(sequence) <= 1:
return [sequence]
first = sequence[0]
rest_perms = get_permutations(sequence[1:])
result = []
for perm in rest_perms:
for i in range(len(perm) + 1):
result.append(perm[:i] + first + perm[i:])
return result
Loading