[Python]pythonchallenge第1关--20131117

pythonchallenge第1关:

http://www.pythonchallenge.com/pc/def/map.html

K-->M

O-->Q

E-->G

即将每个字母+2,那么下面那一大段看起来像乱码的东西按此规律转换应该就是答案了吧。

 1 #!usr/bin/python
 2 # Filename:pythonchallenge1.py
 3 
 4 inputs = raw_input()
 5 word = ''
 6 for char in inputs:
 7     if char == ' ':
 8         print word,
 9         word = ''
10     elif char.isalpha():
11         if char == 'y':
12             word += 'a'
13         elif char == 'z':
14             word += 'b'
15         else:
16             word += chr(ord(char) + 2)
17     else:
18         word += char
19 print word

输入那段文字得到转换结果:

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.

将url中的map-->ocr,进入第二关。

 

---------------------------------------------再来看看上文提到的string.maketrans()是什么---------------------------------------------------------

官方文档说明:

static str.maketrans(from, to)

This static method returns a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals.

If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

str.translate(table[,deletechars])

Return a copy of the s where all characters have been mapped through the map which must be a dictionary of Unicode ordinals (integers) to Unicode ordinals, strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted.

简单来说就是maketrans()将from中的字符一一对应为to中的字符(因此from和to必须等长),并返回一个供translate使用的映射表table。而translate将移除字符串str中deletechars包含的字符,并将剩下的字符按照table中的映射关系进行一一映射。

尝试使用上述两个函数解决这一关的题目:

#!usr/bin/python
# Filename:pythonchallenge1.py

import string

inputs = raw_input()
table = string.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',\
                         'cdefghijklmnopqrstuvwxyzabCDEFGHIJKLMNOPQRSTUVWXYZAB')
print inputs.translate(table)

输出:

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.

逻辑更简单,代码更简单,果然是神奇的python!

posted on 2013-11-17 16:40  小驴车头  阅读(211)  评论(0编辑  收藏  举报