-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCaesar_Cipher.py
More file actions
288 lines (225 loc) · 9.36 KB
/
Caesar_Cipher.py
File metadata and controls
288 lines (225 loc) · 9.36 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#!/usr/bin/env python3
#
# author @danbros
# Pset5 do curso MITx: 6.00.1x (edX)
#
# This file use "type hints", so run with Python 3.6 + or erase them (PEP 526)
### DO NOT MODIFY THIS FUNCTION ###
def load_words(file_name: str) -> list:
"""Depending on the size of the word list, this function may take a while
to finish.
Args:
file_name: the name of the file containing the list of words to load
Returns:
list: a list of valid words. Words are strings of lowercase letters.
"""
print('Loading word list from file...')
# inFile: file
in_file = open(file_name, 'r')
# line: string
line = in_file.readline()
# word_list: list of strings
word_list = line.split()
print(' ', len(word_list), 'words loaded.')
in_file.close()
return word_list
### DO NOT MODIFY THIS FUNCTION ###
def is_word(word_list: list, word: str) -> bool:
"""
Determines if word is a valid word, ignoring capitalization and punctuation
Example:
is_word(word_list, 'bat') returns True
is_word(word_list, 'asdf') returns False
Args:
word_list: list of words in the dictionary.
word: a possible word.
Returns:
bool: True if word is in word_list, False otherwise
"""
word = word.lower()
word = word.strip(r" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
return word in word_list
### DO NOT MODIFY THIS FUNCTION ###
def get_story_string() -> str:
"""Returns: a joke in encrypted text."""
f = open("story.txt", "r")
story = str(f.read())
f.close()
return story
class Message(object):
### DO NOT MODIFY THIS METHOD ###
def __init__(self, text: str):
"""Initializes a Message object
Args:
text: 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)
### DO NOT MODIFY THIS METHOD ###
def get_message_text(self) -> str:
"""Used to safely access self.message_text outside of the class
Returns:
str: self.message_text
"""
return self.message_text
### DO NOT MODIFY THIS METHOD ###
def get_valid_words(self) -> list:
"""
Used to safely access a copy of self.valid_words outside of the class
Returns:
list: a COPY of self.valid_words
"""
return self.valid_words[:]
def build_shift_dict(self, shift: int) -> dict:
"""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.
Args:
shift(int): the amount by which to shift every letter of the
alphabet. 0 <= shift < 26
Returns:
dict: a dictionary mapping a letter (string) to another letter
(string).
"""
# Version 2 lines of Kiwitrader
# lu = 'abcdefghijklmnopqrstuvwxyz'*2 + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'*2
# return {lu[i]: lu[i+shift] for i in range(0, 78) if not 25 < i < 52}
alph_lower = [chr(97 + i) for i in range(26)]
alph_upper = [s.upper() for s in alph_lower]
shift_lower = alph_lower[shift:] + alph_lower[:shift]
shift_upper = alph_upper[shift:] + alph_upper[:shift]
full_alph = alph_lower + alph_upper
full_shift = shift_lower + shift_upper
self.shift_dict = dict(zip(full_alph, full_shift))
return self.shift_dict
def apply_shift(self, shift: int) -> str:
"""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
Args:
shift(int): the shift with which to encrypt the message.
0 <= shift < 26
Returns:
str: the message text (string) in which every character is
shifted down the alphabet by the input shift
"""
s_dict = self.build_shift_dict(shift)
# I cannot make it work that way, Exception KeyError
# ans = ((i, s_dict[i])[i in s_dict] for i in self.message_text)
ans = (s_dict[i] if i in s_dict else i for i in self.message_text)
# ans = []
# for i in self.message_text:
# if i in s_dict:
# ans.append(s_dict[i])
# else:
# ans.append(i)
return ''.join(ans)
class PlaintextMessage(Message):
def __init__(self, text: str, shift: int):
"""Initializes a PlaintextMessage object
A PlaintextMessage obj 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.encrypting_dict (dictionary, built using shift)
self.message_text_encrypted (string, created using shift)
Hint: consider using the parent class constructor so less
code is repeated
Args:
text(str): the message's text
shift(int): the shift associated with this message
"""
# If is the first time of this init(shift does not exist), call super()
if not hasattr(self, 'shift'):
super().__init__(text)
self.shift = shift
self.encrypting_dict = super().build_shift_dict(shift)
self.message_text_encrypted = super().apply_shift(shift)
def get_shift(self) -> int:
"""Used to safely access self.shift outside of the class
Returns:
int: self.shift
"""
return self.shift
def get_encrypting_dict(self) -> dict:
"""Used to safely access a copy self.encrypting_dict outside of the class
Returns:
dict: a COPY of self.encrypting_dict
"""
return dict(self.encrypting_dict)
def get_message_text_encrypted(self) -> str:
"""
Used to safely access self.message_text_encrypted outside of the class
Returns:
str: self.message_text_encrypted
"""
return self.message_text_encrypted
def change_shift(self, shift: int) -> None:
"""Changes self.shift of the PlaintextMessage and updates other
attributes determined by shift (ie. self.encrypting_dict and
message_text_encrypted).
Args:
shift(int): the new shift that should be associated with this
message. 0 <= shift < 26
Returns:
None:
"""
# A hint of Kiwitrader (this same func but oneline) (ignore the lint)
self.__init__(self.message_text, shift)
# My old solve
# self.shift = shift
# self.encrypting_dict = super().build_shift_dict(shift)
# self.message_text_encrypted = super().apply_shift(shift)
# Using property
# @property
# def key_value(self) -> int:
# return self.shift
# @key_value.setter
# def key_value(self, shift):
# self.__init__(self.message_text, shift)
class CiphertextMessage(Message):
def __init__(self, text: str):
"""Initializes a CiphertextMessage object
a CiphertextMessage object has two attributes:
self.message_text (string, determined by input text)
self.valid_words (list, determined using helper function load_words)
Args:
text(str): the message's text
"""
super().__init__(text)
def decrypt_message(self) -> tuple:
"""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 you may choose any of those shifts (and their
corresponding decrypted messages) to return
Returns:
tuple: a tuple of the best shift value used to decrypt the message
and the decrypted message text using that shift value
"""
# Solved, the prob was w_score dont restart to 0, but inside loop, ok
msg_lst = (self.apply_shift(i) for i in range(26))
best = 0
for i, lst in enumerate(msg_lst):
w_score = 0
for w in lst.split():
w_score += is_word(self.valid_words, w)
if w_score > best:
best = w_score
key = i
return (key, self.apply_shift(key))
def decrypt_story():
"""Load the file store.txt, and decript it"""
return CiphertextMessage(get_story_string()).decrypt_message()
WORDLIST_FILENAME = 'words.txt'
if __name__ == "__main__":
print(decrypt_story())