2017-09-08 46 views
-1

我曾嘗試爲我在學校的首個Python項目製作凱撒密碼。我有點從主密碼段的YouTube視頻中複製出代碼,但是當我加密用戶鍵入的消息時,它會執行隨機密碼,而不是輸入到shell中的密鑰。這是代碼:凱撒密碼不正確旋轉字母? (Python)

abc = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz' 

def main(): 
    message = input("What's the message to encrypt/decrypt? ") 
    key = int(input("What number would you like for your key value? ")) 
    choice = input("Choose: encrypt or decrypt. ") 
    if choice == "encrypt": 
     encrypt(message, key) 
    elif choice == "decrypt": 
     encrypt(message, key * (-1)) 
    else: 
     print("Bad answer, try again.") 

def encrypt(message, key): 
    cipherText = "" 
    for letter in message: 
     if letter in abc: 
      newPosition = (abc.find(letter) + key) % 26 
      cipherText += abc[newPosition] 
     else: 
      cipherText += letter 
    print(cipherText) 
    return cipherText 

main() 

有人可以幫我解決這個問題,請。另外請不要讓它變得非常複雜,因爲我是Python的初學者,而且我一點都不瞭解。

謝謝!

+0

看看[ask] – pvg

+0

你沒有將'key'或'message'傳遞給'encrypt'方法。 – KDecker

+0

'encrypt'方法有兩個參數。 – GAVD

回答

0

的問題主要論點是,你在交織字符集大寫和小寫字母。所以當你試圖用角色替換一個角色,比如說前面5個角色時,你實際上是在翻轉角色並提前2-3個角色(取決於你開始的情況)。實現這一點有更好的方法,但事實證明,一個簡單的變化可以使你的代碼按預期方式工作:

newPosition = (abc.find(letter) + key * 2) % 52 

如果您雙擊,當你發現你的替換字符的關鍵,那麼你會被跳過兩字符集中的大寫和小寫字母。而且由於你的加倍鑰匙將永遠是平衡的,你最終會得到同樣的情況。您還需要按照R.Sharp指出的方式將模數相應更改爲52。

+0

謝謝,這解決了我的問題!並感謝所有人幫助我!我不知道這是一個明顯的解決方案哈哈! – Kieran

0
abc = 'AaBbCcDdEeFfGgHhIiJjKKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz' 

def main(): 
    message = input("What's the message to encrypt/decrypt? ") 
    key = int(input("What number would you like for your key value? ")) 
    choice = input("Choose: encrypt or decrypt. ") 
    if choice == "encrypt": 
     encrypt(message, key) 
    elif choice == "decrypt": 
     encrypt(message, key * (-1)) 
    else: 
     print("Bad answer, try again.") 

def encrypt(message, key): 
    cipherText = "" 
    for letter in message: 
     if letter in abc: 
      newPosition = (abc.find(letter) + key) % 26 
      cipherText += abc[newPosition] 
     else: 
      cipherText += letter 
    print(cipherText) 
    return cipherText 

main() 

失蹤的消息,在加密

+0

是的,對不起。我已經在事先請求中解決了這個問題。只是忘了添加。即使有2個參數後,它不起作用:/ – Kieran

1

雖然我同意@glibdud,但還有一個錯誤。 您正在模擬26鍵的值+位置abc。 但abc是52個字符長 - 這樣才能夠解密你加密的東西,你需要改變,要newPosition = (abc.find(letter) + key) % 52

如果你想加密串更加隨心所欲,說包括一些標點符號或數字字符,替代26或52與計算出的加密字符串的長度進行比較。

+0

非常感謝您的幫助!沒有意識到答案基本上在我面前這一整天xd。 – Kieran

0
(abc.find(letter) + key) % 26 

因爲abc既有大寫也有小寫混合。應用於字符「C」的鍵(例如:2)將導致「D」而不是「E」。

+0

謝謝,在上面的評論中,它說'鍵* 2)%52'這是有效的。所以通過添加'* 2'解決了問題:D – Kieran