Python Challenge 第一关

偶然在网上看到这个,PYTHON CHALLENGE,利用Python语言闯关,觉得挺有意思,就记录一下。

第0关应该算个入口吧,试了好几次才试出来,没什么代码就不写了。计算一个结果出来就行。

第一关,给了一个图和一段文字。那段文字明显是经过加密的:

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.


然后图上有三行提示:"K->M    O->Q   E->G"。我开始想法很简单,将这段字符串中的这三个字母替换一下。。结果出来还是看不懂,就知道自己想法太简单了。

再仔细看了看图中的三行提示,发现替换后的字母都是替换前字母的后2位,于是想试一试将所有的字母往后移两位。首先的想法就是处理ASCII码:

def changeStr0(srcStr):
    dstStr = ''
    for i in srcStr:
        if i.islower():
            dstStr += chr((ord(i) - ord('a') + 2) % 26 + ord('a'))
        else:
            dstStr += i
    return dstStr

判断源字符串中的每一项,若是小写字母,将它的ASCII码后移两位再转换回字母,为了避免后面几位加了2得到其他符号,这里使用ASCII码的差模26。

将这个字符串解码后得到下面的句子:

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.

这时候才知道还有string.maketrans()这个函数。于是在解释器里输入 help(string.maketrans) 得到:

maketrans(...)
    maketrans(frm, to) -> string
   
    Return a translation table (a string of 256 bytes long)
    suitable for use in string.translate.  The strings frm and to
    must be of the same length.

这个函数会根据frm和to这两个字符串返回一个table,两个参数长度要一样,把frm中对应的字母换成to中对应的字母。返回值table用来给string.translate函数做参数。又去查了下string.tanslate():

translate(s, table, deletions='')
    translate(s,table [,deletions]) -> string
   
    Return a copy of the string s, where all characters occurring
    in the optional argument deletions are removed, and the
    remaining characters have been mapped through the given
    translation table, which must be a string of length 256.  The
    deletions argument is not allowed for Unicode strings.

这个函数根据table将s中的字母替换,并删掉可选参数deletions中字符。于是有了第二版:

def changeStr1(srcStr):
    frm = string.letters[0:26]
    to = string.letters.lower()[2:28]
    table = string.maketrans(frm, to)
    return srcStr.translate(table)

这个版本就简单多了。然后利用写好的函数,将url中的map处理一下得到ocr,就可以进入下一关了:http://www.pythonchallenge.com/pc/def/ocr.html

原文地址:https://www.cnblogs.com/dukeleo/p/3458005.html