[英]Substitution Cipher in Python with a Letter Map
我想做替換密碼但有一個字母映射而不是隨機字母。 到目前為止,我的代碼只對其進行隨機化,並且不使用字母映射,因為我不知道該怎么做。
#Substitution Cipher
def subst_cipher(alphabet):
alphabet = list(alphabet)
letter_map = {'a': 'm', 'b': 'k', 'c': 'n', 'd': 'o', 'e': 'c', 'f': 'v', 'g': 'w', 'h': 'z', 'i': 'b', 'j': 't', 'k': 'y', 'l': 'r', 'm': 'x', 'n': 'd', 'o': 'u', 'p': 'p', 'q': 'a', 'r': 'i', 's': 's', 't': 'f', 'u': 'q', 'v': 'e', 'w': 'l', 'x': 'g', 'y': 'j', 'z': 'h'}
random.shuffle(alphabet)
return ''.join(alphabet)
測試用例:
#What it should do
subst_cipher(letter_map,'Figaro')
returns: 'vbwmmu # I think
#what it does now
subst_cipher('Figaro')
returns: 'oaFirg'
幫助!
您可以使用"".join()
和生成器表達式來使用替換表映射字符串中的每個字母。
def subst_cipher(letter_map, text):
return "".join(letter_map.get(c, "?") for c in text)
我選擇將不在地圖中的字母替換為?
而不是徹底崩潰( letter_map[c]
)。
用上面的字母映射調用它:
letter_map = {
"a": "m",
"b": "k",
# ... elided for brevity...
}
print(subst_cipher(letter_map, "figaro"))
產出
vbwmiu
這或多或少是您所期望的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.