好吧,我承认,昨天用urlopen失败,今天用却成功了,否则,这关只能是找别人现成的答案了……
http://www.pythonchallenge.com/pc/def/linkedlist.php
不管是查看源代码还是直接点网页,都可以看到http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345 及 网页中and the next nothing is 44827。
题意搞清楚了,就是把后面的数字替换原地址中的数字,过程中肯定不会一帆风顺,但是,没办法预测到会出什么问题,只能见招拆招,见人说鬼话了……
import string
from urllib2 import urlopen
prefix = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='
num = '12345'
circle = 0
while True:
circle += 1
text = urlopen(prefix + num).read()
print text
length = len('the next nothing is ')
index = text.find('the next nothing is ')
if index == -1:
if text.find('two') == -1:
break;
else :
num = str((int(num) / 2))
else :
index = index + length
num = text[index:]
话说,为什么这里又不居中了……
这个是终结版的代码,最开始,我是用正则表达式的,很简单,
re.compile('[0-9]')来匹配数字。
第一个坎是‘Yes. Divide by two and keep going.',这样,就加上了index = text.find(),如果没找到,则除2,因为不知道未来会有什么,先这样。随便,把数字12345改成当时的16044。
第二个坎也是最后一个坎,There maybe misleading numbers in the text. One example is 82683. Look only for the next nothing and the next nothing is 63579。
我初始的正则表达式很给面子的得到了8268363579,就是不知道这个往下会如何。
想想本关中,数字的位置除了divide two以外,都固定在最后,于是更改成现在这个样子。当然,可能还有更好的写法,就是split,直接把最后一位切出来,判断是否为数字,如果不是,再判断是否除2……
session = text.split()
last = session[-1]
这样的话,不用我之前辛辛苦苦地找位置了。
python确实很漂亮,试试找找python的项目源代码读一读。