这个是 Python Challenge 的 Level 1。
g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.
看这个图一眼就知道是凯撒密码,或者叫移位密码。
下面是我的实现代码(de_caesar_cipher)和我认为最佳的实现代码(de_caesar_cipher_new)。
# coding=utf-8
# caesar_cipher
# K-M O-Q E-G
import stringORD_A = ord('a')
ORD_z = ord('z')
ALPHA_COUNT = 52/2
def get_alpha_map():
alpha_set = {}
for x in range(ORD_A, ord('z')+1):
alpha_set[chr(x)] = x - ORD_A
return alpha_set
def de_caesar_cipher(string, offset):
alpha_set = get_alpha_map()
de_string = ''
for s in string:
de_string += chr(ORD_A + (alpha_set[s] + ALPHA_COUNT + offset) % ALPHA_COUNT) if s in alpha_set else s
return de_string
def get_translate():
i = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
e = "CDEFGHIJKLMNOPQRSTUVWXYZABcdefghijklmnopqrstuvwxyzab"
return string.maketrans(i, e)
def de_caesar_cipher_better(string):
return string.translate(get_translate())
if __name__ == "__main__":
given = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
print(de_caesar_cipher(given, 2)) print(de_caesar_cipher_better(given))
pass
运行结果:
i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url.
i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url.
[Finished in 0.5s]
点评: