Posts Tagged ‘python challenge’

Python Challenge level 13: “call him”

For level 13 you need a tip from the last challenge.

Hint 1: phone that evil
Hint 2: link to phonebook.php, which returns an XMLRPC error
Fact 1: we know from the previous level that “Bert is evil”

#!/usr/bin/env python
import xmlrpclib
server = xmlrpclib.Server('http://www.pythonchallenge.com
/pc/phonebook.php')
## we'll need to discover Server API
# print server.system.listMethods()
print server.phone('Bert')

555-ITALY

This one was shorter than expected. Now to Level 14.

Read the rest of this entry »

Python Challenge level 12: “dealing evil”

Level 12 requires some hex-observation.

Hint 1: image evil1.jpg with a shuffled deck and five piles

The name evil1 seems suspicious, so maybe we can find something else poking around.

Fact 1: there are more evil?.jpg and an evil2.gfx

Fact 2: when inspected in an hex editor the gfx file seems to have several images interleaved. You don’t have to be a genius to recognize a JPEG header, but the GIF87a is much more obvious. Not everybody is used to reading binary files, but simply by watching you can get the idea that each file is shuffled every 5 bytes. So the task will be deshuffling evil2.gfx into 5 piles

Fact 3: when trying to retrieve file evil4.jpg a text appears “http://www.pythonchallenge.com/pc/return/evil4.jpg” and the source code is “Bert is evil! go back!”. This is not useful right now, but keep it in mind. It may come in handy in the future.

That’s a lot of text for one post ;) At least the task is clear. Two lines of code should suffice:

#!/usr/bin/env python
info=open("evil2.gfx").read()
[open("12_f%d.dat" %i, "w").write(info[i::5]) for i in range(5)]

My image viewer doesn’t really care for the file extension, so “.bin” suits me fine. Anyway you could allways use the file command in case yours cares.

Once we view the images, we get the link for Level 13.

Read the rest of this entry »

Python Challenge level 11: “odd even”

Level 11 requires playing with images once again.

Fact 1: the image cave.jpg seems to have half ot its pixels blanked
We’ll assume odd and even pixels belong to different images. This snippet will put me out of my misery and let me know ;)

import Image
src = Image.open("cave.jpg")
w,h = src.size[0], src.size[1]
print "Image info:",src.format, src.size, src.mode
new = Image.new(src.mode,(w//2, h))

for i in range(w*h):
    y, x = divmod(i, w)
    p = src.getpixel((x,y))
    if i%2: #even==info, odd==photo
        new.putpixel((x/2,y/2+h//2),p)
    else:
        new.putpixel((x/2,y/2),p)
new.save('11.jpg')

Now it’s readable. “evil“. Next is Level 12.

Read the rest of this entry »

Python Challenge level 10: “where are you looking at”

Level 10 doesn’t have anything new.

Hint 1: len(a[30]) = ?
Hint 2: a = [1, 11, 21, 1211, 111221,
Fact 1: 'a' is the 'look and say sequence'.
Im normally pretty good finding numeric patterns, but I must confess that I had to look up this one. I suppose I don't have the right mindset to mix numbers and words.

a=['1']
for i in range(30):
    elem=a[-1]+’?’
    next=[]
    start=0
    for end in range(len(elem)):
        if elem[end]!=elem[start]:
            next.append(str(end-start)+elem[start])
            start=end
    a.append(”.join(next))
print len(a[-1])

The output is:

5808

That's it. Coming up next, Level 11.

Read the rest of this entry »

Python Challenge level 9: “connect the dots”

Level 9 needs some more drawing.

Hint 1: first+second=?

import Image,ImageDraw
im = Image.new('RGB', (500,500))
draw = ImageDraw.Draw(im)

first=[146,399,163,403, ...]  # chunked
second=[156,141,165,135, ...] # chunked

for i in range(0, len(first), 2):
    draw.line(first[i:i + 4], fill='white')
for i in range(0, len(second), 2):
    draw.line(second[i:i + 4], fill='white')
im.save('09.jpg')

Is it a cow? Nope, it’s Level 10.

EDIT: Thanks to Meng Tan for the comment below. I didn’t know that PIL could (also) do that ;)

The script would be as follows:

import Image,ImageDraw
im = Image.new('RGB', (500,500))
draw = ImageDraw.Draw(im)
first=[146,399,163,403, ...]  # chunked
second=[156,141,165,135, ...] # chunked
draw.polygon(first,fill='white')
draw.polygon(second,fill='white')
im.save('09.jpg')
Read the rest of this entry »

Python Challenge level 8: “working hard?”

Level 8 is easy.

Hint 1: Where is the missing link?
Hint 2: un and pn are provided
Fact 1: the bee links to a page in a protected directory
Fact 2: BZh91AY seems to be a bzip2 header (says Google)

import bz2
un= 'BZh91AY&SYAx....' #complete the string here
pw= 'BZh91AY&SYx9....' #likewise
print "user:",bz2.decompress(un)
print "pass:",bz2.decompress(pw)

Which gives:

user: huge
pass: file

And on to Level 9.

Note that the values of un and pn aren’t complete since they had HEX characters that do not seem to render correctly in the plugin I use for code in WordPress. Have it in mind if you are just copying and pasting your way through the Python Challenge. I advise strongly against that though. The beauty is in the journey itself ;-) If you don’t think highly of the game by now, just wait until we get to the levels for grown-ups.

Read the rest of this entry »

Python Challenge level 7: “smarty”

Level 7 needs the Image module.

Fact 1: The PNG file has a weird grey area, so the information must be encoded there.

import Image
im = Image.open("oxygen.png")
print "Image info:",im.format, im.size, im.mode

#we'll limit the grey zone
y_begin = 0
while True:
    p = im.getpixel((0, y_begin))
    if p[0] == p[1] == p[2]:
        break
    y_begin += 1
x_end = 0
while True:
    p = im.getpixel((x_end, y_begin))
    if not p[0] == p[1] == p[2]:
        break
    x_end += 1
print "Y first coordinate:", y_begin,"nX last coordinate:",x_end

message=[]
for i in range(0,x_end,7):
    p = im.getpixel((i, y_begin))
    message.append(chr(p[0]))
print ''.join(message),
#First run gives: [105, 110, 116, 101, 103, 114, 105, 116, 121]
message=[105, 110, 116, 101, 103, 114, 105, 116, 121]
print '(',''.join([chr(x) for x in message]),')'

After running the script:

smart guy, you made it. the next level is [105, 110, 116, 101, 103, 114, 105, 116, 121] ( integrity )

And that sends us to Level 8

Read the rest of this entry »

Python Challenge level 6: “now there are pairs”

Level 6 deals again with linked lists.

Hint 1: Image is a zipper and there is a comment in the page (<!– <– zip –>). Once we open channel.zip, there are some more hints: “welcome to my zipped list“.
Hint 2: start from 90052
Hint 3: answer is inside the zip

import zipfile,re
idx="90052"
file = zipfile.ZipFile("channel.zip", "r")
history = []
while True:
    history.append(idx)
    data = file.read(idx+".txt")
    print "File",idx+":\t"+ data
    idx="".join(re.findall('[0-9.]',data))
    if len(idx)==1:
        break
#Collect the comments
print ''.join([file.getinfo(i+'.txt').comment for i in history])
File 90052:     Next nothing is 94191
File 94191:     Next nothing is 85503
[...]
File 67824:     Next nothing is 46145
File 46145:     Collect the comments.
****************************************************************
****************************************************************
**                                                            **
**   OO    OO    XX      YYYY    GG    GG  EEEEEE NN      NN  **
**   OO    OO  XXXXXX   YYYYYY   GG   GG   EEEEEE  NN    NN   **
**   OO    OO XXX  XXX YYY   YY  GG GG     EE       NN  NN    **
**   OOOOOOOO XX    XX YY        GGG       EEEEE     NNNN     **
**   OOOOOOOO XX    XX YY        GGG       EEEEE      NN      **
**   OO    OO XXX  XXX YYY   YY  GG GG     EE         NN      **
**   OO    OO  XXXXXX   YYYYYY   GG   GG   EEEEEE     NN      **
**   OO    OO    XX      YYYY    GG    GG  EEEEEE     NN      **
**                                                            **
****************************************************************
 **************************************************************

… and in hockey.html

it’s in the air. look at the letters.

Hm… the letters in “hockey” are made out of “o, x, y, g, e, n”. Level 7, here we go!

UPDATE: A ‘\’ was missing in the code. Thanks to PSquid for reporting.

Read the rest of this entry »

Python Challenge level 5: “peak hell”

Level 5 is the first challenge specific to Python since it involves the pickle module in charge of Python object serialization.

Hint 1: pronounce it
Fact 1: there is a refference to a file named banner.p in the html source, so we’ll download it and see
Fact 2: once depickled, it looks like a run-length encoding

import urllib,pickle
url='http://www.pythonchallenge.com/pc/def/banner.p'
obj=pickle.load(urllib.urlopen(url))
for line in obj:
    print ''.join(map(lambda pair: pair[0]*pair[1], line))

The output, in a pretty *nix banner command fashion, is:

channel

And that is Level 6.

Read the rest of this entry »

Python Challenge level 4: “follow the chain”

Level 4 requires some web scraping. Nice :)

Hint 1: urllib may help. DON’T TRY ALL NOTHINGS, since it will never end. 400 times is more than enough
Hint 2: linkedlist.php?nothing=12345

import urllib,re
url='http://www.pythonchallenge.com/pc/def/
     linkedlist.php?nothing='
seed="12345"
for i in range(400):
    text=urllib.urlopen(url+seed).read()
    seed="".join(re.findall(r"nothing is (\d+)",text))
    try :
        int(seed)
        print "   Next:",seed
    except :
        print "   Last:",text
        break

When we get to 92118 the message is:

Yes. Divide by two and keep going.

So we’ll reset the seed to 46059

peak

Great. To Level 5.

Read the rest of this entry »