I thought I would write my first python function for this one. They appear to need to be at the top of the script though with a little casual searching I couldn’t confirm that.
Python 2.7.2 Solution
This got me there but is pretty flaky and needed manually fixing to get to the answer.
import urllib, re
count = 1
def getNextCode(lastCode):
while True:
try:
page = urllib.urlopen('http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%s' % lastCode).read()
code = re.findall('(?<=and the next nothing is )\w*',page)
print "Code %i is %s. \nPage message was '%s'.\nPage tried was http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%s'.\n" % (count, code[0], page, lastCode)
return code
except (IndexError, NameError):
print "Error: Page message was '%s'\nPage was: http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%s'." % (page,lastCode)
return False
nextCode = getNextCode('12345')
count = 1
for count in range (1,400):
if count == 84:
nextCode[0] = int(nextCode[0])/2
nextCode = getNextCode(nextCode[0])
Python 3.2.3 Solution
This deals with the message that you must divide by two when you get 16044 as a code. It also loads the page. The 3.2.3 has a very different urllib approach. 3.2.3 seems to do crazy stuff with variable types.
import urllib.request, re, webbrowser
count = 1
def getNextCode(lastCode):
while True:
try:
if lastCode == '16044': lastCode = str(16044 / 2)
page = urllib.request.urlopen('http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%s' % lastCode).read()
code = re.findall(r'(?<=and the next nothing is )\w*',page.decode("utf-8"))
print ("\nCode %i is %s.\nPage tried was http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%s'.\nPage message was '%s'." % (count, code[0], lastCode, page.decode("utf-8")))
return code
except (IndexError, NameError):
print ("Error: Page message was '%s'\nPage was: http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%s'." % (page,lastCode))
return False
nextCode = getNextCode('12345')
count = 1
for count in range (1,400):
if nextCode != False:
answer = nextCode[0]
nextCode = getNextCode(nextCode[0])
else:
new = 2 # open in a new tab, if possible
test4url = "http://www.pythonchallenge.com/pc/def/" + urllib.request.urlopen('http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%s' % answer).read().decode("utf-8")
webbrowser.open(test4url,new=new)
break
print ("Done.")