Python Challenge 第 1 关攻略:What about making trans?

Python Challenge1 关攻略:What about making trans?


题目地址
http://www.pythonchallenge.com/pc/def/map.html


题目内容

everybody thinks twice before solving this.
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.

General tips:
- Use the hints. They are helpful, most of the times.
- Investigate the data given to you.
- Avoid looking for spoilers.

Forums: Python Challenge Forums

注意:官网给的论坛链接已经 404


题目解法
页面标题写着:做点翻译怎么样?

URL 地址写着 map ,即映射

联系图片的内容,知道这是一个字母映射
KMOQEG

Python 中试验发现:

>>> ord('M') - ord('K')
2
>>> ord('Q') - ord('O')
2
>>> ord('G') - ord('E')
2

映射后字母的 ASCII 码是映射前字母的 ASCII 码加 2 得到的。

用这个规律把题目给的像乱码一样的字符串转码,注意要略过标点符号,另外注意不要超出字母边界。

msg = "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."

def trans(x):
    if x.isalpha():
        x = chr(ord(x) + 2)
        if x.isalpha():
            return x
        else:
            return chr(ord(x) - 26)
    else:
        return x

new_msg = []

for i in msg:
    new_msg.append(trans(i))

new_msg = ''.join(new_msg)
print(new_msg)

得到的结果是:

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() 方法,然而该方法在 Python 3 中被 str.maketrans() 取代。
语法:str.maketrans(intab, outtab)
intab 是输入表, outtab 是输出表,返回一个由 ASCII 码组成的映射表,以字典形式存储。
str.maketrans() 改写一下程序:

intab = 'abcdefghijklmnopqrstuvwxyz'
outtab = 'cdefghijklmnopqrstuvwxyzab'
trantab = str.maketrans(intab, outtab)

msg = "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."

msg = msg.translate(trantab)

print(msg)

得到的结果一样,而且程序简洁许多。

按照提示,对 URL 使用 translate 函数:

intab = 'abcdefghijklmnopqrstuvwxyz'
outtab = 'cdefghijklmnopqrstuvwxyzab'
trantab = str.maketrans(intab, outtab)

url = 'map'

url = url.translate(trantab)

print(url)

得到 ocr ,替换 map 到浏览器中,回车即可进入下一关:
http://www.pythonchallenge.com/pc/def/ocr.html

猜你喜欢

转载自blog.csdn.net/jpch89/article/details/81269717
今日推荐