2015-11-03 53 views
-1

我在加密大寫字母時遇到了問題,例如如果消息是COMPUTING IS FUN,關鍵字是GCSE,我應該得到JRFUBWBSN LL KBQ,但是我的實際結果是xftipkpgb zz ype。這個結果既不是正確的字母也不是資本。任何幫助表示讚賞加密大寫字母python vigenere

    message = input('\nenter message: ') 
        keyword = input('enter keyword: ') 
        def chr_to_inta(char): 
         return 0 if char == 'Z' else ord(char)-64 
        def int_to_chra(integer): 
         return 'Z' if integer == 0 else chr(integer+64) 
        def add_charsa(msg, key): 
         return int_to_chr((chr_to_int(msg) + chr_to_int(key)) % 26) 


        def chr_to_int(char): 
         return 0 if char == 'z' else ord(char)-96 
        def int_to_chr(integer): 
         return 'z' if integer == 0 else chr(integer+96) 
        def add_chars(msg, key): 
         return int_to_chr((chr_to_int(msg) + chr_to_int(key)) % 26) 

        def vigenere(message, keyword): 

         keystream = cycle(keyword) 
         new = '' 
         for msg in message: 
          if msg == ' ': # adds a space 
           new += ' ' 
          elif 96 < ord(msg) < 123: # if lowercase 
           new += add_chars(msg, next(keystream)) 

          else: # if uppercase 
           new += add_charsa(msg, next(keystream)) 

         return new 

        new = vigenere(message, keyword) 
        print('your encrypted message is: ',new) 
+2

didnt我們已經做到這一點... HTTP://stackoverflow.com/questions/33442220/itertools-cycle-in-vigenere-密碼導致的問題與空間-python/33442864#33442864 –

+0

我們上次添加空格,現在我需要做大寫字母。我已經嘗試添加三個與其他類似的新功能,但現在它們返回一個大寫字母'Z'而不是小寫字母'',它不起作用,並且我被卡住了,首先想到 – MrBeard

+0

,你有兩個定義'add_chars'並且沒有'add_charsa'的定義。第二,你需要確保'add_charsa'調用你的新函數,而不是你的舊函數,即它應該返回int_to_chra((chr_to_inta(msg)+ chr_to_inta(key))' –

回答

0

,因爲你不似乎讓我說的話:

def add_charsa(msg, key): 
    return int_to_chr((chr_to_int(msg) + chr_to_int(key)) % 26) 

是你目前有。這一點,你會得到你的壞輸出:

>>> vigenere('COMPUTING IS FUN','GCSE') 
'xftipkpgb zz ype' 

這是因爲你沒有改變return語句此函數來調用新的大寫功能。如果你改變了return語句:

def add_charsa(msg, key): 
    return int_to_chra((chr_to_inta(msg) + chr_to_inta(key)) % 26) 
#notice the change in function calls from int_to_chr -> int_to_chra, and chr_to_int -> chr_to_inta 

然後你會得到預期:

>>> vigenere('COMPUTING IS FUN','GCSE') 
'JRFUBWBSN LL KBQ' 

這是值得的,要知道,如果你的鑰匙有大寫和小寫字母的混合,這不管用。很好。我反而會改變你的keystream是:keystream = cycle(keyword.lower())那麼你的函數是:

def add_charsa(msg, key): 
     return int_to_chra((chr_to_inta(msg) + chr_to_int(key)) % 26) 
    #notice the call to chr_to_int(key) because key will always be lower case 
+0

哎呀,我現在感覺有點傻。非常感謝 – MrBeard