2015-06-14 65 views
0

我創建了一個簡單的程序,用於在用戶輸入的字符串上執行Caeser密碼。當過去的結束範圍內在列表內移動?

爲了讓轉移越過列表的末尾並返回到開頭,我只是簡單地複製了該列表的所有列表值。

是否有一個更pythonic的方式來實現這個結果,以便它將轉移回到開始,並繼續轉移,如果移動超過列表範圍的結束?

while True: 
    x = input("Enter the message you would like to encrypt via a Caeser shift; or type 'exit': ") 
    if x == 'exit': break 
    y = int(input("Enter the number by which you would like to have the message Caeser shifted: ")) 
    alphabet = list('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz') 
    encoded = '' 
    for c in x: 
     if c.lower() in alphabet: 
      encoded += alphabet[alphabet.index(c)+y] if c.islower() else alphabet[alphabet.index(c.lower())+y].upper() 
     else: 
      encoded += c 
    print(encoded) 

回答

1

如果你想這樣做,這樣,那麼你最好的選擇是使用模運算來計算alphabet指數:

while True: 
    x = input("Enter the message you would like to encrypt via a Caeser shift; or type 'exit': ") 
    if x == 'exit': break 
    y = int(input("Enter the number by which you would like to have the message Caeser shifted: ")) 
    alphabet = 'abcdefghijklmnopqrstuvwxyz' 
    encoded = '' 
    for c in x: 
     if c.lower() in alphabet: 
      i = (alphabet.index(c.lower()) + y) % 26 
      encoded += alphabet[i] if c.islower() else alphabet[i].upper() 
     else: 
      encoded += c 
    print(encoded) 

一些注意事項:不需要將您的字母表轉換爲列表:字符串也可迭代;一個dictionary可能是一個更好的替代數據結構。

+0

這正是我所期待的。我還沒有熟悉模塊化算術,但它看起來像是一個偉大的技巧,在我的武庫。名單上的好點也是如此。 – roflmyeggo

1
x = "message" 
y = 10 # Caeser shift key 
alphabet = list('abcdefghijklmnopqrstuvwxyz') 
encoder = dict(zip(alphabet, alphabet[y:]+alphabet[:y])) 
encoded = "".join(encoder[c] for c in x) 
+0

我很喜歡這個。使用字典是解決這個問題的好方法,可以消除對模塊化算術的需求(如xnx指出的那樣)。謝謝邁赫迪。 – roflmyeggo

2

這是我寫的最好的pythonic方式。您甚至不需要列表,因爲每個字符都有一個具有預定範圍的ASCII值。只是玩弄它。

def encrypt(text,key): 
    return "".join([ chr((ord(i) - 97 + key) % 26 + 97) if (ord(i) <= 123 and ord(i) >= 97) else i for i in text]) 

ord(i)爲您提供ascii值。 97是'a'的值。因此ord(i) - 97與在您的列表中搜索i的索引相同。添加密鑰來轉移。 chrord相反,它將ascii值轉換回字符。

所以只需要在該方法中的一行代碼。

+2

「Pythonic」:你繼續使用這個詞。我不認爲這意味着你的想法。 – xnx

+0

哈哈不是很確定。但是我敢肯定的是我的代碼很少是單調的!但是,你是否在追蹤我的活動? – Aditya

+0

@xnx感謝評論反正。我想我並不需要吹噓這種單線解決方案。 – Aditya