我正在撰寫一個程式來解密訊息,并且只假設解密訊息的最大出現字母是“e”。沒有給出班次編號。下面的代碼是我的作業。我只能硬編碼班次號碼來解密給定的訊息,但如果訊息改變了我的代碼當然不起作用。
from collections import Counter
import string
message = "Zyp cpxpxmpc ez wzzv fa le esp delcd lyo yze ozhy le jzfc qppe Ehz ypgpc rtgp fa hzcv Hzcv rtgpd jzf xplytyr lyo afcazdp lyo wtqp td pxaej hteszfe te Escpp tq jzf lcp wfnvj pyzfrs ez qtyo wzgp cpxpxmpc te td espcp lyo ozye esczh te lhlj Depaspy Slhvtyr"
#frequency of each letter
letter_counts = Counter(message)
print(letter_counts) # Print the count of each element in string
#find max letter
maxFreq = -1
maxLetter = None
letter_counts[' '] = 0 # Don't count spaces zero count
for letter, freq in letter_counts.items():
print(letter, ":", freq)
maxLetter = max(letter_counts, key = letter_counts.get) # Find max freq letter in the string
print("Max Ocurring Letter:", maxLetter)
#right shift for encrypting and left shift for descripting.
#predict shift
#assume max letter is 'e'
letters = string.ascii_letters #contains 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
shift = 15 #COMPUTE SHIFT HERE (hardcode)
print("Predicted Shift:", shift)
totalLetters = 26
keys = {} #use dictionary for letter mapping
invkeys = {} #use dictionary for inverse letter mapping, you could use inverse search from original dict
for index, letter in enumerate(letters):
# cypher setup
if index < totalLetters: #lowercase
# Dictionary for encryption
letter = letters[index]
keys[letter] = letters[(index shift) % 26]
# Dictionary for decryption
invkeys = {val: key for key, val in keys.items()}
else: #uppercase
# Dictionary for encryption
keys[letter] = letters[(index shift) % 26 26]
# Dictionary for decryption
invkeys = {val: key for key, val in keys.items()}
print("Cypher Dict", keys)
#decrypt
decryptedMessage = []
for letter in message:
if letter == ' ': #spaces
decryptedMessage.append(letter)
else:
decryptedMessage.append(keys[letter])
print("Decrypted Message:", ''.join(decryptedMessage)) #join is used to put list inot string
# Checking if message is the same as the encrypt message provided
#Encrypt
encryptedMessage = []
for letter in decryptedMessage:
if letter == ' ': #spaces
encryptedMessage.append(letter)
else:
encryptedMessage.append(invkeys[letter])
print("Encrypted Message:", ''.join(encryptedMessage)) #join is used to put list inot string
代碼的加密部分不是必須存在的,它只是為了檢查。如果有人可以幫助修改我的代碼/給我一些關于預測轉換部分的提示,那就太好了。謝謝!
代碼輸出:
Cypher Dict {'a': 'p', 'b': 'q', 'c': 'r', 'd': 's', 'e': 't', 'f': 'u', 'g': 'v', 'h': 'w', 'i': 'x', 'j': 'y', 'k': 'z', 'l': 'a', 'm': 'b', 'n': 'c', 'o': 'd', 'p': 'e', 'q': 'f', 'r': 'g', 's': 'h', 't': 'i', 'u': 'j', 'v': 'k', 'w': 'l', 'x': 'm', 'y': 'n', 'z': 'o', 'A': 'P', 'B': 'Q', 'C': 'R', 'D': 'S', 'E': 'T', 'F': 'U', 'G': 'V', 'H': 'W', 'I': 'X', 'J': 'Y', 'K': 'Z', 'L': 'A', 'M': 'B', 'N': 'C', 'O': 'D', 'P': 'E', 'Q': 'F', 'R': 'G', 'S': 'H', 'T': 'I', 'U': 'J', 'V': 'K', 'W': 'L', 'X': 'M', 'Y': 'N', 'Z': 'O'}
Decrypted Message: One remember to look up at the stars and not down at your feet Two never give up work Work gives you meaning and purpose and life is empty without it Three if you are lucky enough to find love remember it is there and dont throw it away Stephen Hawking
Encrypted Message: Zyp cpxpxmpc ez wzzv fa le esp delcd lyo yze ozhy le jzfc qppe Ehz ypgpc rtgp fa hzcv Hzcv rtgpd jzf xplytyr lyo afcazdp lyo wtqp td pxaej hteszfe te Escpp tq jzf lcp wfnvj pyzfrs ez qtyo wzgp cpxpxmpc te td espcp lyo ozye esczh te lhlj Depaspy Slhvtyr
uj5u.com熱心網友回復:
這包括三個組成部分:
- 查找具有最大頻率的字符:
test_str = "" # your string
counter = Counter(test_str)
keys = sorted(counter, key=counter.get, reverse=True)
res = keys[1] if keys[0] == " " else keys[0]
- 計算班次:
shift = ord('e') - ord(res)
- 加密/解密字串,這很簡單,因為您現在知道了轉變
uj5u.com熱心網友回復:
這樣的事情應該允許您基于以下假設計算移位:原始訊息中頻率最高的字母是'e':
letter_counts = Counter(message)
e_encrypted = [k for k, v in letter_counts.items() if v == max(count for c, count in letter_counts.items() if c != ' ')][0]
shift = (ord('e') - ord(e_encrypted)) % 26
或者,展開理解以便于理解:
letter_counts = Counter(message)
e_encrypted, max_v = None, 0
for k, v in letter_counts.items():
if v > max_v and k != ' ':
e_encrypted, max_v = k, v
shift = (ord('e') - ord(e_encrypted)) % 26
它執行以下操作:
- 在
message使用Counter類時計算字符的頻率 - 找到最大頻率,以及具有該最大頻率的字符
- 將移位設定為等于該字符的 ascii 值與字母之間的差
'e'(模 26)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442609.html
上一篇:我想將編碼的字串作為輸出。但不能
