2017-10-10 3 views
1

私はテキスト入力が与えられ、出力は入力ですが、アルファベットで2に沿ってシフトされるような暗号を作っています。例えば、 "hi"は "jk"に変わります。私は "y"が "b"に変わることができるようにリストをラップするのに問題があります。 プレーンテキストは設定入力です。 キーがシフトする2Pythonでラップリストを囲んで

charset=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] # characters to be encrypted 

def caesar_encrypt(plaintext,key): 

    plaintext = plaintext.upper() # convert plaintext to upper case 
    ciphertext = "" # initialise ciphertext as empty string 

    for ch in plaintext: 
     if ch == " ": 
      pass 
     else: 
      index = charset.index(ch) 
      newIndex = index + key 
      shiftedCharacter = charset[newIndex] 
      ciphertext += shiftedCharacter 
      print(ciphertext) 
    return ciphertext 
+4

試し 'newIndexが=(インデックス+キー)%LEN(文字セット)'(_integer modulo_を満たす) –

+1

インデントは単なる問題を引き起こす可能性が台無しにされています。 – tadman

+0

もう一つの注意として、 'charset =" ABCDEFGHIJKLMNOPQRSTUVWXYZ "'という言葉だけでなく、はるかにコンパクトです。 'import string'を実行してから' string.ascii_uppercase'を使うこともできます。 –

答えて

2

だけ変更:

newIndex = index + key 

た:

newIndex = (index + key) % len(charset) 

この方法は、値ラップアラウンドグレースフルこの中のy

Modulo (%) documentation

0

である、あなたはこれを試すことができます。

import string 

converter = {string.ascii_uppercase[i]:string.ascii_uppercase[i+2] for i in range(24)} 
+0

私が見る限り、これは 'z'のために折り返されません。モジュロが必要ですが、これは他の答えでカバーされています。 –

関連する問題