Python Challenge 第四題,pythonchallenge
這一題沒有顯示提示,只有一幅圖片,圖片也看不出什麼名堂,於是直接查看源碼,源碼如下:
<html><head> <title>follow the chain</title> <link rel="stylesheet" type="text/css" href="../style.css"></head><body><!-- urllib may help. DON'T TRY ALL NOTHINGS, since it will never end. 400 times is more than enough. --><center><a href="linkedlist.php?nothing=12345"><img src="chainsaw.jpg" border="0"/></a><br><br><font color="gold"></center>Solutions to previous levels: <a href="http://wiki.pythonchallenge.com/"/>Python Challenge wiki</a>.<br><br>IRC: irc.freenode.net #pythonchallenge</body></html>
可以看到,解題需要用到urllib,提示我們不要去一個一個地嘗試noting,因為這數量特別多,遠遠不止四百次(最終證明其實不需要四百次,一百二十多次就行了),既然這麼多,那肯定不能手動去試了,但是可以讓電腦自動去訪問提取nothing值。點擊圖片,我們便獲得了第一個nothing值44827,再修改URL,獲得下一個nothing值,發現沒個nothing頁面最後都會有這句話“and the next nothing is ”後面接著一個數字(當然,因為URL的需要,我們把它理解為一個字串,剛開始投機取巧認為這數字是五位的,後來出現四位的,又認為是四位或五位的,再後來有三位的。。。於是還是老老實實寫關於提取最後不限位元數字字元的代碼),從而猜想,那個可以獲得答案相關資訊的頁面內容會與這些均不同,可以通過內容最後是否是數字字元來判斷,最後代碼如下:
import urllib.requestname='http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='finalNum='44827'#nothing's number stringwhile 1: f=urllib.request.urlopen(name+x) content=f.read().decode('utf-8') print(content) #輸出頁面內容,方便查看到最後的解題資訊 finalNum=[] content=list(content) content.reverse() for i in content: #提出頁面內容最後的數字字元 if i.isdigit(): finalNum.append(i) else: break finalNum.reverse() finalNum=''.join(finalNum) if not finalNum: #判斷頁面最後內容是不是數字字元,如果不是,則跳出迴圈 break
當迴圈結束時候的那個頁面資訊是“Yes. Divide by two and keep going”,上一個頁面為“and the next nothing is 16044”,於是修改finalNum的值為‘8022’,重新啟動程式,最後獲得答案