2017-04-04 8 views
1

これは私がVigenére暗号を扱うために使用している関数です。私の問題は、入力にスペースがあると、メッセージと共にエンコードされるということです。出力メッセージのスペースを変更しないでください。どうやってやるの?メッセージ内にVigenère暗号のハンドルスペースを作成するにはどうすればよいですか?

def vigenere(): 
    global encoded 
    global message 
    global book 

    while len(book) < len(message): 
     book += book 

    book = book[:len(message)] 

    encoded = "" 

    for char in range(len(message)): 
     newchar = ord(message[char]) + ord(book[char]) - 194 
     newchar %= 25 
     encoded += chr(newchar + 97) 

    print(encoded) 
+1

何をしようとしていますか?スペースをどこに入力する必要がありますか?それはあなたの質問はかなり不明です。 –

+0

私はvigenereコードの結果にスペースをインポートしようとしています。たとえば、ユーザーの入力に空白が含まれている場合、空白を正確に同じ場所に置き、文字に変更することはできません。 –

+0

私のソリューションをチェックしてください。 –

答えて

0

Vigenère暗号を使用する前に、スペース内の文字列内のすべての場所を取得してください。 、そして、

import re  

def space_indices(string): 
    return [s.start() for s in re.finditer(' ', string)] 

あなたの入力からすべてのスペースを削除します:あなたは、正規表現を使用していることを行うことができます

def remove_spaces(string): 
    return string.replace(' ', '') 

そして、それは代わりにそれを印刷するエンコードされたメッセージを返すように、あなたのヴィジュネル暗号機能を再定義します:あなたは、その後、すべてのスペースのインデックスを見つける新しい関数を定義し、これらの指標を保存し、スペースを削除し、unspにヴィジュネル暗号を適用することができます

def vigenere(): 
    # encode your message... 
    return encoded 

結果にスペースを挿入します。

def space_preserving_vigenere(message): 
    space_indices = space_indices(message) 
    unspaced_msg = remove_spaces(message) 
    encoded = vigenere(unspaced_msg) 
    inserted_spaces = 0 
    for index in space_indices: 
    actual_index = index + inserted_spaces 
    encoded = encoded[:actual_index] + ' ' + encoded[actual_index:] 
    inserted_spaces = inserted_spaces + 1 
    return encoded 
+0

ありがとうございます!!!! :) –

関連する問題