【发布时间】:2020-11-12 11:14:54
【问题描述】:
假设输入了一条消息,并且您想通过将单词“up the alphabet”中的每个字母移动 x 个空格来对其进行加密。例如“cat”移动了一个空格变成了“dbu”:
我正在尝试构建一个字典,其中大写和小写字母作为键,重复字母(移动“移位”字母数)作为值。例如 shift=1 d={a:b, b:c...A:B, B:C}。每次“班次”改变时,这个字母都会改变。请让我知道我哪里出错了。请参阅:def build_shift_dict(self, shift) 下面。提前致谢!:
class Message(object):
### DO NOT MODIFY THIS METHOD ###
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)
### DO NOT MODIFY THIS METHOD ###
def get_message_text(self):
'''
Used to safely access self.message_text outside of the class
Returns: self.message_text
'''
return self.message_text
### DO NOT MODIFY THIS METHOD ###
def get_valid_words(self):
'''
Used to safely access a copy of self.valid_words outside of the class
Returns: a COPY of self.valid_words
'''
return self.valid_words[:]
import string
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).
'''
stringLower = string.ascii_lowercase
stringUpper = string.ascii_uppercase
Alphabet = list(stringLower + stringUpper)
dictionary = {}
string2Lower = list(string.ascii_lowercase[shift:] + string.ascii_lowercase[0:shift])
string2Upper = list(string.ascii_uppercase[shift:] + string.ascii_uppercase[0:shift])
combinedList = string2Lower.append(string2Upper)
for key in Alphabet:
for value in combinedList:
dictionary[key] = value
combinedList.remove(value)
return dictionary
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
'''
result=''
dictionary = self.build_shift_dict(shift)
messageString = str(Message)
for letter in messageString:
if letter in dictionary.keys:
result += dictionary[i]
return result
【问题讨论】:
-
您可能想要删除该行:combinedList.remove(value)。
标签: python encryption