前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 ># python # # Challenge # Level 1

# python # # Challenge # Level 1

作者头像
滚神大人
发布2019-09-10 18:53:14
6420
发布2019-09-10 18:53:14
举报
文章被收录于专栏:趣Python趣Python

这个是 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函数可以实现任意的移位或者映射密码。
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-02-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 趣Python 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档