首页
学习
活动
专区
圈层
工具
发布

# python # # Challenge # Level 1

这个是 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)。

代码语言:javascript
复制
# 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

运行结果:

代码语言:javascript
复制
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]

点评:

  1. maketrans和translate是python内置的实现简单加密的两个函数,前一个函数是做映射,后一个函数是基于映射做的解码转换函数,实现原理比较简单,python的底层经过C语言的优化。
  2. 封装之后的好处,使用maketrans函数可以实现任意的移位或者映射密码。
下一篇
举报
领券