2017-02-20 52 views
1

我正在嘗試讓我的塞薩爾密碼迴繞。不幸的是,我不知道如何去實施它。這裏是我的代碼,因爲它是目前:塞薩爾密碼繞回

maximum_character = unciphered_text[0] 
maximum_count = unciphered_text.count(unciphered_text[0]) 
for char in unciphered_text: 
    if char is not " ": 
     if unciphered_text.count(char) > maximum_count: 
      maximum_character = char 

print("The most frequent character used is: ", maximum_character) 

ASCII_maximum = maximum_character.lower() 
ASCII_number = ord(ASCII_maximum) 
print(ASCII_number) 

shift_distance = ord('e')-ASCII_number 
print("The shift distance is: ", shift_distance) 

def caesar_cipher(unciphered_text, shift_distance): 
    ciphered_text = "" 
    for char in unciphered_text: 
     if char.isalpha(): 
      cipher_process = ord(char)+shift_distance 
      if cipher_process > ord('z'): 
      cipher_process -= 26 
      post_translation = chr(cipher_process) 
      ciphered_text += post_translation 
    return ciphered_text 

answer = caesar_cipher(unciphered_text, shift_distance) 
print(answer) 

雖然它最終消除在這個過程中的空間和適當的標點符號我的代碼可以翻譯輸入到的東西可讀。

Input: Frzdugv glh pdqb wlphv ehiruh wkhlu ghdwkv; Wkh ydoldqw qhyhu wdvwh ri ghdwk exw rqfh. Ri doo wkh zrqghuv wkdw L bhw kdyh khdug, Lw vhhpv wr ph prvw vwudqjh wkdw phq vkrxog ihdu; Vhhlqj wkdw ghdwk, d qhfhvvdub hqg, Zloo frph zkhq lw zloo frph 

Output: Cowardsdieman_timesbeforetheirdeathsThevaliantnevertasteofdeathbutonceOfallthewondersthatI_ethaveheardItseemstomemoststrangethatmenshouldfearSeeingthatdeathanecessar_endWillcomewhenitwillcome 

Desired Output: COWARDS DIE MANY TIMES BEFORE THEIR DEATHS; THE VALIANT NEVER TASTE 
OF DEATH BUT ONCE. OF ALL THE WONDERS THAT I YET HAVE HEARD, IT 
SEEMS TO ME MOST STRANGE THAT MEN SHOULD FEAR; SEEING THAT DEATH, A 
NECESSARY END, WILL COME WHEN IT WILL COME. 
+0

所以,你想知道如何使它跳過非字母字符?你能發佈一些輸入,電流輸出和所需的輸出嗎? – TemporalWolf

回答

0

您必須將它們轉錄到你的答案:

for char in unciphered_text: 
    if char.isalpha(): 
     cipher_process = ord(char.upper()) + shift_distance 
     if cipher_process > ord('Z'): 
      cipher_process -= 26 
     if cipher_process < ord('A'): # Deal with underflow 
      cipher_process += 26 
     post_translation = chr(cipher_process) 
     ciphered_text += post_translation 
    else: # skip, but include non-alphabetic characters 
     ciphered_text += char 

此外,你需要.upper()炭要轉換爲大寫,並處理字符以下A下溢。

樣本輸出(事後添加的回報):

COWARDS DIE MANY TIMES BEFORE THEIR DEATHS; THE VALIANT NEVER TASTE 
OF DEATH BUT ONCE. OF ALL THE WONDERS THAT I YET HAVE HEARD, IT SEEMS 
TO ME MOST STRANGE THAT MEN SHOULD FEAR; SEEING THAT DEATH, A NECESSARY 
END, WILL COME WHEN IT WILL COME 
+0

謝謝。我的輸出更具可讀性。但是,輸出應該打印出'y',而是打印出「 - 」。這就是我的意思 – Amaranthus

+0

懦夫在死亡之前死於man_ times;勇士從來沒有嘗過死亡的味道,但曾經。在我所聽到的所有奇蹟中,我覺得最奇怪的是人們應該害怕;看到死亡,必要的結局,它會在什麼時候到來 – Amaranthus

+0

非常感謝你現在工作得更好! – Amaranthus