Sunday, 24 April 2011

Python Challenge #004 - linkedlist

Clicking the image leads to linkedlist.php?nothing=12345, which suggests replacing the value at the end of the URL. Let's define a function to get the next value.
>>> import sys
>>> from urllib.request import urlopen
>>> BASE_URL = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='
>>> def next_nothing(n):
...   text = urlopen(BASE_URL + n).read().decode()
...   m = re.match('and the next nothing is ([0-9]+)', text)
...   if not m: print('\n\n' + text + '\n')
...   n = m.group(1)
...   sys.stdout.write(n + ', '); sys.stdout.flush()
...   return n
... 

Note that this will raise an AttributeError when the regular expression fails to match and m.group is called when m is None.
>>> n = '12345'
>>> while True: n = next_nothing(n)
... 
92512, 64505, ...

Feed in the next value and repeat as necessary.
>>> n = '50010'
>>> while True: n = next_nothing(n)
... 
29193, 89924, ...

No comments:

Post a Comment