我創建了以下函式,根據給定的移位將字母表中的每個字母與其對應的編碼字母配對:
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def build_cipher(shift):
'''
Description: takes in shift (an integer representing the amount the letter key in the dictionary is shifted from its corresponding letter) and returns a dictionary containing all letters and their corresponding letters after the shift. This is achieved through subtracting the shift from the number corresponding to the letter, and using modulo 26.
>>> build_cipher(-3)
{'a': 'x', 'b': 'y', 'c': 'z', 'd': 'a', 'e': 'b', 'f': 'c', 'g': 'd', 'h': 'e', 'i': 'f', 'j': 'g', 'k': 'h', 'l': 'i', 'm': 'j', 'n': 'k', 'o': 'l', 'p': 'm', 'q': 'n', 'r': 'o', 's': 'p', 't': 'q', 'u': 'r', 'v': 's', 'w': 't', 'x': 'u', 'y': 'v', 'z': 'w'}
'''
return {alphabet[i]: alphabet[(i shift) % 26] for i in range(0, 26)}
接下來我需要定義一個函式 encode 接收文本和移位,并回傳編碼的文本。我還需要使用我的 build_cipher 函式來做到這一點。到目前為止,我有:
def encode(text, shift):
'''
Description: takes in a text string and shift. Returns the text string encoded based on the shift.
>>> encode('test', -4)
>>> encode('code', 5)
'''
#return (text[(i shift) % 26] for i in range(0,26))
#return (build_cipher(shift) for text in alphabet)
#return (build_cipher(shift) for text in range(0,26))
我對 return 陳述句的每次嘗試都在底部的評論中。沒有一個作業正常,我不確定如何準確地做到這一點,因為 build_cipher 作為字典回傳。任何關于我如何實作這一目標的提示表示贊賞。
uj5u.com熱心網友回復:
您已經創建了密碼構建函式,現在讓我們使用它來創建密碼并將其應用于文本中的每個字符。我在這里使用get來使不在密碼中的字符保持不變。
def encode(text, shift):
cipher = build_cipher(shift)
return ''.join(cipher.get(c, c) for c in text)
例子:
>>> encode('good morning', 4)
'kssh qsvrmrk'
>>> encode('kssh qsvrmrk', -4)
'good morning'
注意。您的代碼目前無法處理大寫字母,這可能是您想要解決的問題;)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315517.html
下一篇:使用字典創建凱撒密碼,只輸出一項
