Python Challenge(4)

続いて第4問
謎はページタイトル「follow the chain」と画像リンク先からすぐに解けた。

from urllib import request

url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345'
count = 0
while (count < 400):
    print(count)
    res = request.urlopen(url).read().decode()
    print(res)
    next = res[-5:]
    print(next)
    url = url[:-5] + next
    count = count + 1
    print(url)

7回目に「and the next nothing is 6306」と4桁の数字が現れたので次のリクエストで失敗。
正規表現で対応。

from urllib import request
import re

url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345'
count = 0
while (count < 400):
    print(count)
    res = request.urlopen(url).read().decode()
    print(res)
    match = re.search("\d+$", res)
    if match:
        next = match.group()
    else:
        break
    print(next)
    url = re.sub("\d+$", next, url)
    count = count + 1
    print(url)

198回目に「Yes. Divide by two and keep going.」と出て中断。
直前の数値の半分にurlを変えて続行すると10回目で「peak.html」となり〆