pythonchallenge之我的解答(一)

来源:互联网 发布:印度用手擦屁股 知乎 编辑:程序博客网 时间:2024/05/01 04:18

http://www.pythonchallenge.com/

 

好玩的网站,如何进入下一题全靠推理及代码实现,目前做了5道题了,待继续。

 

第0题 http://www.pythonchallenge.com/pc/def/0.html
说明:计算2的38次方。
代码:
print 2**38
结果:得到274877906944,根据提示,修改url,得到下一题地址:http://www.pythonchallenge.com/pc/def/274877906944.html

第1题 http://www.pythonchallenge.com/pc/def/map.html
说明:将所给的字符串中的每个字母用其之后的第二个字母代替
代码:
import string
x = '''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 x.translate(string.maketrans(string.lowercase, string.lowercase[2:] + string.lowercase[:2]))

结果:得到字符串: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"得到下一题地址:http://www.pythonchallenge.com/pc/def/ocr.html

第2题 http://www.pythonchallenge.com/pc/def/ocr.html
说明:阅读page source,发现一句话"find rare characters in the mess below:"
代码:
import urllib2
urldata = urllib2.urlopen('http://www.pythonchallenge.com/pc/def/ocr.html').readlines()
startline = urldata.index('find rare characters in the mess below:/n') + 1
print filter(lambda x: x.isalpha(), ''.join(urldata[startline:-1]))

结果:equality


第3题 http://www.pythonchallenge.com/pc/def/equality.html
说明:在page source中的数据中找出前后各有且仅有3个大写字母的小写字母
代码:
import urllib2
import re
urldata = urllib2.urlopen('http://www.pythonchallenge.com/pc/def/equality.html').readlines()
startline = urldata.index('<!--/n') + 1
print ''.join(re.findall('(?:^|[^A-Z])[A-Z]{3}([a-z])[A-Z]{3}(?:[^A-Z]|$)', ''.join(urldata[startline:-1])))

结果:linkedlist

第4题 http://www.pythonchallenge.com/pc/def/linkedlist.php
说明:根据page source中的提示,打开http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345,得到and the next nothing is 92512,继续,迭代400次。过程中会碰到特殊情况,需另外对待,具体见代码。
代码:
import urllib2
urladdr_pre = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='
urladdr_suf = '12345'
for i in range(0, 400):
    urldata = urllib2.urlopen(urladdr_pre + urladdr_suf).read()
    print urldata
    if urldata.find('the next nothing is ') >= 0:
        urladdr_suf = urldata.split('the next nothing is ')[-1]
    elif urldata.find('Yes. Divide by two and keep going.') >= 0:
        urladdr_suf = str(int(urladdr_suf) / 2)
    else:
        break

结果:peak.html