2016-12-30 21 views
-1

這個密碼使用一個關鍵字,並重復它到一個輸入消息的長度,然後將它們都轉換爲數字(關鍵字和消息在字母表中的每個字母的位置),然後將它們相加在一起,然後被SUPPOSED轉換回到字母表中的字母。如何將列表中元素的位置更改爲實際元素(關鍵字密碼)?

alpha =   ["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"] 
keyword = input("Please enter a keyword: ") 

sentence = input("Enter message: ") 

new_keyword = [] 
while len(keyword) < len(sentence): 
    keyword = keyword + keyword 
keyword = (keyword.lower()) 


for letters in keyword: 
    pos1 = alpha.index(letters) + 1 
    new_keyword.append(pos1) 
print (new_keyword) 

new_sentence = [] 

for letters in sentence: 
    pos2 = alpha.index(letters) + 1 
    new_sentence.append(pos2) 
print (new_sentence) 

joined = [x + y for x, y in zip(new_keyword, new_sentence)] 
print (joined) 

這是我的代碼

我需要找到一種方法來重新打開連接列表到字母又名加密消息

請幫助

+1

「」.join(joined)? –

+0

可能重複的[連接項列表中的字符串](http://stackoverflow.com/questions/12453580/concatenate-item-in-list-to-strings) –

+0

不,我想改變加入列表中的元素回到阿爾法列表 –

回答

0

到目前爲止,您已經轉移的信以適當的量存儲,但仍然具有存儲的序數(或數字)值。

問題1是處理換行過去26的字母(例如z(26)+ a(1)= 27)。

問題2是使用alpha數組將數值變回數字。

我已經將打印語句留在了所以你可以看到發生了什麼。

# Original code - unedited 
alpha = ["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"] 
keyword = input("Please enter a keyword: ") 

sentence = input("Enter message: ") 

new_keyword = [] 
while len(keyword) < len(sentence): 
    keyword = keyword + keyword 
keyword = (keyword.lower()) 


for letters in keyword: 
    pos1 = alpha.index(letters) + 1 
    new_keyword.append(pos1) 
print (new_keyword) 

new_sentence = [] 

for letters in sentence: 
    pos2 = alpha.index(letters) + 1 
    new_sentence.append(pos2) 
print (new_sentence) 

joined = [x + y for x, y in zip(new_keyword, new_sentence)] 
print (joined) 

# Take any value over 26 and wrap it back round (so z + 1 = a) 

for i in range(len(joined)): 
    if joined[i] > 26: 
     joined[i] -= 26 

print (joined) 

# Convert each numeric value back into its character, using the alpha list 

ciphertext = [] 

for letters in joined: 
    char = alpha[letters - 1] 
    ciphertext.append(char) 

print(ciphertext) 

一個稍微簡單的方法是使用ord()和chr()函數。這些將字符分別轉換爲ASCII值並返回。

+0

謝謝你soo了 –