2015-05-19 35 views
0
text='hijklqrs'  
def encrypt(shift_text,shift_amount, direction): 
    cipher_text=[] 
    for i in shift_text:      
     if direction is right:     
      cipher_text.append(text[(text.index(i) + shift_amount) % 26])  
     else: 
      cipher_text.append(text[(text.index(i) - shift_amount) % 26])   
    output = ''.join(cipher_text) 
    return output 

到目前爲止,這是我創建的代碼,但我遇到的問題是,我需要能夠將我的文本左移或右移我的函數中的方向參數。我不確定如何將代碼添加到我想要移動到左側的代碼中。因此,例如,當我將h放入函數並且移位量爲2並且方向爲左時,它將返回f添加一個方向發送加密字符python代碼

+0

能否請您確認您的代碼縮進了'encrypt'功能翻譯您的原文? –

+0

代碼縮進我已經改變了我的if語句,以反映我認爲所需的移位方向是正確的。如果發送到右側,則參數方向將添加移位量,否則將被減去。 –

回答

0
def rotate(alphabet,shift): 
    return alphabet[shift:] + alphabet[:shift] 

print rotate("abcdefghijk",2) 

你再配對起來使用字典或string.transtab,並與您的移動文字

from string import maketrans,ascii_lowercase 
N = -13 #shift ammount (use negative for "left" and positive for "right") 
tab = maketrans(ascii_lowercase,rotate(ascii_lowercase,N)) 
encoded = "hello world".translate(tab) 
decode_tab = maketrans(rotate(ascii_lowercase,N),ascii_lowercase) 
decoded = encoded.translate(decode_tab) 
print encoded,"--->",decoded