python - 使用 OOP 逻辑的 Ceaser 密码
问题描述
下面是我的基于类的 Ceaser 密码的代码,这是针对 MIT 6.001 Ps4b.py
问题:
在代码文件(test case#02)末尾的测试用例中,预期的输出是(24, 'hello')。
而程序的实际输出是(2, 'hello')
这是有道理的,因为第 330-332 行:
plaintext = PlaintextMessage('hello', 2)
print('Expected Output: jgnnq')
print('Actual Output:', plaintext.get_message_text_encrypted())
创建一个将 shift 值设置为 2 的 PlaintextMessage 实例。其中 'jgnnq' 是 'hello' 的加密。
第 335-337 行:
ciphertext = CiphertextMessage('jgnnq')
print('Expected Output:', (24, 'hello'))
print('Actual Output:', ciphertext.decrypt_message())
这里: string = 'jgnnq' 解密字符串 = 'hello' 最佳因子实际是 2,但预期是 24 应该打印一个元组,其中包含用于(解密)字符串和解密字符串(即 'hello')的因子。
所以我的问题是为什么测试用例#02 的预期“最佳因子”是 24,而用于(解密)字符串的因子是 2。
测试用例由 MIT OCW 提供,我没有修改。
代码:
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
WORDLIST_FILENAME = 'words.txt'
words = load_words(WORDLIST_FILENAME)
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)
#self.valid_words = [word for word in text.split() if is_word(words, word)]
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_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).
'''
lowercase_letters = ascii_lowercase
uppercase_letters = ascii_uppercase
# alphabet = lowercase_letters + uppercase_letters
# alphabet_shifted = alphabet[-shift:] + alphabet[:-shift]
lowercase_shifted = lowercase_letters[shift:] + lowercase_letters[:shift]
uppercase_shifted = uppercase_letters[-shift:] + uppercase_letters[:-shift]
# shift_dict = {letter: shift for letter, shift in zip(alphabet, alphabet_shifted)}
shift_dict_lowercase = {letter: shift for letter, shift in zip(lowercase_letters, lowercase_shifted)}
shift_dict_uppercase = {letter: shift for letter, shift in zip(uppercase_letters, uppercase_shifted)}
return [shift_dict_lowercase, shift_dict_uppercase]
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_lowercase, shift_dict_uppercase = self.build_shift_dict(shift)
plain_msg = self.message_text
encrypted_msg = []
for char in plain_msg:
if char in ascii_lowercase:
encrypted_msg.append(shift_dict_lowercase[char])
elif char in ascii_uppercase:
encrypted_msg.append(shift_dict_uppercase[char])
else:
encrypted_msg.append(char)
# encrypted_msg = [shift_dict_lowercase.get(char, char) for char in plain_msg]
return ''.join(encrypted_msg)
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.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.__init__(self.message_text, 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)
# need to optimize this:
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
'''
# using a dictonary to get the max number of valid words in a string
# have to figure out how to see if a word is valid after applying the
# shift to it.
results = {}
words_found = {n: [] for n in range(26)}
for n in range(26):
for word in self.message_text.split():
m = Message(word)
word = m.apply_shift(-n)
# print(word)
if is_word(words, word):
results[n] = results.get(n, 0) + 1
words_found[n].append(word)
# print(results)
# print(words_found)
# print(max(results))
best_factor = max(results)
return best_factor, PlaintextMessage(self.message_text, -best_factor).get_message_text_encrypted()
# num_words_per_factor = {n:len(words_found[n]) for n in range(26)}
# best_factor =
# print(best_factor)
# plain_text_msg = PlaintextMessage('Hello, Cat, Dog, Kate', 0)
# print(plain_text_msg.get_message_text())
# encrypted_msg = plain_text_msg.apply_shift(3)
# print(encrypted_msg)
# cipher_msg = CiphertextMessage(encrypted_msg)
# decrypted_msg = cipher_msg.decrypt_message()
# print(decrypted_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())
#TODO: WRITE YOUR TEST CASES HERE
#TODO: best shift value and unencrypted story
#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())
解决方案
对于使用某个因素进行解密,您应该在加密操作方面朝相反的方向移动。
请注意,24 = -2(模 26)。
预期的输出显然正在寻找适用于编码过程的移位值。
推荐阅读
- java-stream - Hazelcast Jet java.util.streaming
- tensorflow - 如何将 GCS 凭据添加到 tensorflow?
- node.js - 如何访问 bookshelf.js 中的 knex/querybuilder raw?
- sql - SQL中的慢速选择查询,表只有200万条记录
- python - RuntimeError:线程只能启动一次 Python Tkinter webserver
- ruby-on-rails - Ruby on Rails - 可能无法匹配的约束:[:id]
- java - 我们可以同时从多个线程访问同一个实例的同步方法和非同步方法吗?
- linux-kernel - Unix 共享库和 VDSO 内存映射
- apache-spark - Spark 客户端模式 - YARN 为驱动程序分配一个容器?
- swift - Swift 选项 - 为什么 var a:Int?一个?= 4 返回零