星期五, 十月 31, 2008

python解决一个面试题

                Test  your  WebQ!

          69  66  20  79          6F   75   20   63
          61  6E  20  72          65   61   64   20
          74  65  69  73          20    77   65   20
          77  61  6E  74          20   79    6F  75

Are you read to shape the future of the web?

实际上不难看出应该是一个16进制标识的字符矩阵
用python写程序有:
s = '''
          69  66  20  79          6F   75   20   63
          61  6E  20  72          65   61   64   20
          74  65  69  73          20    77   65   20
          77  61  6E  74          20   79    6F  75
      '''
print ''.join(map[lambda x: chr(int(x,16)), s])

result:
if you can read teis we want you
源贴见http://groups.google.com/group/pongba/browse_thread/thread/1891961524ea733e

其中有几个python的函数和特性的妙用:
1、用join函数来把一个字符的数组拼成一个字符串。''.join()的妙用可以处理此类问题
2、chr()函数用来转换ACII码数字为字符,int()函数传入参数转换16进制为十进制
3、lambda定义单行函数很适合此处的处理
4、map()函数可以对一个list中的各元素执行一个function后,形成一个新的list。等同于[(lambda x:chr(int(x,16)))(n) for n in s.split()]