3 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
我意識(shí)到這個(gè)答案并沒(méi)有真正回答你的問(wèn)題,但我認(rèn)為無(wú)論如何它都是有用的。以下是使用字符串方法實(shí)現(xiàn)caesar密碼的另一種方法:
def caesar(plaintext, shift):
alphabet = string.ascii_lowercase
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
table = string.maketrans(alphabet, shifted_alphabet)
return plaintext.translate(table)
實(shí)際上,由于字符串方法是在C中實(shí)現(xiàn)的,因此我們將看到此版本的性能提升。這就是我認(rèn)為的“pythonic”方式。

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
你需要cipherText = ""在for循環(huán)開(kāi)始之前移動(dòng)。你每次循環(huán)都要重置它。
def caesar(plainText, shift):
cipherText = ""
for ch in plainText:
if ch.isalpha():
stayInAlphabet = ord(ch) + shift
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
finalLetter = chr(stayInAlphabet)
cipherText += finalLetter
print "Your ciphertext is: ", cipherText
return cipherText
添加回答
舉報(bào)