-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathps4c.py
More file actions
220 lines (162 loc) · 6.95 KB
/
ps4c.py
File metadata and controls
220 lines (162 loc) · 6.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# Problem Set 4C
# Name: neelima-j
# Time Spent: 0:50
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
'''
return self.valid_words.copy()
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).
'''
vowels_original = list(VOWELS_LOWER)+list(VOWELS_UPPER)
vowels_permutaion = list(vowels_permutation)+list(vowels_permutation.upper())
dict_vowels = dict(zip(vowels_original,vowels_permutation))
dict_consonants = dict(zip(CONSONANTS_LOWER+CONSONANTS_UPPER,CONSONANTS_LOWER+CONSONANTS_UPPER))
map_dict = dict_vowels|dict_consonants
return map_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
'''
encrypted = ''
for letter in self.message_text:
if letter.isalpha():
encrypted += transpose_dict[letter]
else:
encrypted +=letter
return encrypted
class EncryptedSubMessage(SubMessage):
def __init__(self, text):
'''
Initializes an EncryptedSubMessage object
text (string): the encrypted message text
'''
self.message_text = text
self.valid_words = load_words(WORDLIST_FILENAME)
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
'''
vowel_permutations = get_permutations(VOWELS_LOWER)
final_dict = {}
max_score = 0
best_message = ''
for perm in vowel_permutations:
score = 0
decoded_string = ''
encode_dict = self.build_transpose_dict(perm)
decode_dict = dict(zip(encode_dict.values(),encode_dict.keys()))
for word in self.message_text.split(' '):
decoded_word = ''
for letter in word:
if letter.isalpha():
decoded_word += decode_dict[letter]
else:
decoded_word += letter
if is_word(self.get_valid_words(), decoded_word):
score += 1
decoded_string += ' ' + decoded_word
if score >= max_score:
max_score = score
best_message = decoded_string
return best_message
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