1
def caesar(plaintext,shift):  
    alphabet=["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"]  

    #Create our substitution dictionary  
    dic={}  
    for i in range(0,len(alphabet)):  
        dic[alphabet[i]]=alphabet[(i+shift)%len(alphabet)]  

    #Convert each letter of plaintext to the corrsponding  
    #encrypted letter in our dictionary creating the cryptext  
    ciphertext=("")  
    for l in plaintext.lower():  
            if l in dic:  
                l=dic[l]  
                ciphertext+=l
            return ciphertext  

#Example useage  
plaintext="the cat sat on the mat"  
print "Plaintext:", plaintext  
print "Cipertext:", (caesar(plaintext,29)) 

密文只打印一个字母,而不是在凯撒移位中打印“明文”变量。我希望它打印整个句子。

谢谢

4

3 回答 3

8

这是因为你return ciphertext的缩进错误。您从 for 循环的第一次迭代返回。(缩进在 Python 中很重要!)

    for l in plaintext.lower():  
            if l in dic:  
                l=dic[l]  
                ciphertext+=l
            return ciphertext  # Indented to match level of `if`.

修复它。

    for l in plaintext.lower():  
        if l in dic:  
            l=dic[l]  
            ciphertext+=l
    return ciphertext

几个指针

  1. 无需列出代码中的所有字母,您只需设置alphabets = string.ascii_lowercase.
  2. 您不需要存储变量dic[l],只需执行ciphertext += dic[l].
于 2013-07-24T18:24:33.763 回答
3

用 string.translate 做得更好:)

import string
def caesar(plaintext,shift):  
    alphabet=["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"]
    alphabet_shifted = alphabet[shift:]+alphabet[:shift]
    tab =    string.maketrans("".join(alphabet),"".join(alphabet_shifted))
    return plaintext.translate(tab)
于 2013-07-24T18:41:37.510 回答
2

您需要修复 return 语句的缩进:

for l in plaintext.lower():  
    if l in dic:  
       l=dic[l]  
       ciphertext+=l
    # <-- if you return here, then you will loop only once.      
return ciphertext  
于 2013-07-24T18:25:22.757 回答