Category: Python

Python Challenges- Code Log

Have been working on Python Challanges by Nadev Samat and yes those are pretty tough and interesting at the same time. I tend to pickup stuff and leave it in the middle so this time I have decided to log my progress by posting code for each challenge I solve and hence keep a code and progress log simultaneously.

Challenge 0:

This one was pretty simple and just required:

>>>pow(2, 38)

on the terminal.
Answer was 274877906944

Challenge 1:

Went dumb(as originally I am) and tried to solve this one by hand, but realization came in after reading the first line and hence switched to code:

>>> import string
>>> str = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj";
>>> intab = "abcdefghijklmnopqrstuvwxyz"
>>> outab = "cdefghijklmnopqrstuvwxyzab"
>>> from string import maketrans
>>> trantab = maketrans(intab, outab)
>>> print str.translate(trantab)

Answer was ocr

Challenge 2:

>>>file = open('temp.txt')
>>>key = """\n!#%$&()+*@[]_^{}"""
>>> new2 =""
>>> for letter in str:
... if letter not in key:
... new2 += letter
>>> print(new2)

Answer was equality

Challenge 3:

>>>file = open('temp.txt')
>>>pat = re.compile('''
... [^A-Z] # any character except a capital letter
... [A-Z]{3} # three capital letters
... ( # the beginning of a capturing group
... [a-z] # one lowercase letter
... ) # the end of the group
... [A-Z]{3} # three capital letters
... [^A-Z] # any character except a capital letter
... ''', re.VERBOSE)
>>>  re.findall(pat,str)

Answer was linkedlist

Had too google a lot for challenges 3 and 4 as my regex and python knowledge are pretty nascent. But yes, I will be completing all the 31 challenges and posting those here.

Challenge 4:

Enjoyed this one, very little google was required and the code was pretty straight forward and this was the first time I used Python to fetch online resources. Here is the final code. This ran with a hiccup as I had to change the value of ‘stringholder’ once as per the instructs, but finally did the job:

>>> stringholder = '12345'
>>> url = ''
>>> for x in range(0,399):
... req = urllib2.Request(url+stringholder)
... response = urllib2.urlopen(req)
... fullStr =
... list = re.findall('\d+', fullStr)
... length = len(list)
... stringholder = list[length - 1]
... print stringholder

Answer was peak

Challenge 5:

Another tough one, finding that banner.p was a task. I got to know about pickling from this one & the output, man I was totally blown away:

>>> import urllib, pickle
>>> url = ''
>>> stream = urllib.urlopen(url)
>>> object = pickle.load(stream)
>>> stream.close()
>>> print object #hint: output of banner program by Unix
>>> for item in object:
... print "".join(i[0]*i[1] for i in item)

Answer was channel

Challenge 6:

Phewww, Man, this puzzle was exhausting. You get started with 3 clues: ‘zip’, ‘Now there are pairs’ and ‘channel’. It gives a weak idea that Python zip module is to be used. Hence, Altering the page url to ‘’ from channel.html gives us a zip file. I unzipped this file to find lots of files with ‘nothings'(remember?) and a readme file. Now, there are 2 hints in the readme file, first is: “Start with 90052” and “Answer is inside the zip”. Being Lazy as I am, I ignored the 2nd advice completely and followed the LinkedList approach of extracting the nothings and following those but now for a much larger dataset(~1000). Here’s the initial code below:

>>> import zipfile
>>> zip = zipfile.ZipFile(open('', 'r'))
>>> nothing = '90052.txt'

>>> while True:
... raw_data =, None)
... print raw_data
... nothing = int(raw_data.split()[-1])
... nothing = str(nothing)+'.txt'

Just when I thought I was done I got this:

Next nothing is 46145
Collect the comments.

I had to modify the code and the final code looked like:

>>> import zipfile
>>> zip = zipfile.ZipFile(open('', 'r'))
>>> nothing = '90052.txt'
>>> comments = []
>>> while True:
...     raw_data =, None)
...     print raw_data
...     nothing = int(raw_data.split()[-1])
...     nothing = str(nothing)+'.txt'
...     comments.append(zip.getinfo(nothing).comment)
print "".join(comments)

This leaves us with the answer, hockey and only if at all it was so easy. I entered this into the url and got this: it’s in the air. look at the letters.

Taking a closer look at the hockey reveals that the answer is oxygen.

Challenge 7:

First things first, through this one I got introduced to the PIL(Python Imaging Library). I had to download and install it as an external module using the help of this link(plus ofcourse a bit of scavenging on stackoverflow). Coming back to the Image being shown in challenge 7, with some pixel manipulation in the middle(once again I omitted the fact that the pixel manipulation was exactly in the middle and tried to play around by printing the random pixel rgba values from the picture).

This was the final code which led to the final answer:

>>> from PIL import Image
>>> original ="oxygen.png")
>>> y = original.size[1]/2
>>> print "".join([chr(original.getpixel((x,y))[0]) for x in range(0, original.size[0],7)])

After running this code, I got the following:

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

The answer was integrity.

Challenge 8:

As compared to the last few puzzles, this one was relatively easy. Our first clue is the text at the bottom of the page: “Where is the missing link?”. Moving the cursor on the image of the fly indicates that the image is actually a hyperlink and clicking on it brings up a username, password authentication box with a cryptic text “The server says: inflate”. From here nowhere to go, I decided to delve into the source and found “un” and “pw”, which are actually encoded bz2 streams(Ok, Ok I admit I did not find about the stream format on my own) and here is some relevent info regarding bz2 streams. Had to use Python to decompress the streams to reveal the username and password:

>>> import bz2
>>> un = 'BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084'
>>> pw = 'BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03$ \x00!\x9ah3M\x13<]\xc9\x14\xe1BBP\x91\xf08'
>>> bz2.decompress(un)
>>> bz2.decompress(pw)

Challenge 9:
Puzzle 9 tells us to “connect the dots”. The Source reveals 2 sets of values which can only be co-ordinate values. Plotting the coordinate values give us the image of a bull(took trial and error, I tried ox too).
Code is given below:

>>> from PIL import Image
>>> im ='RGB', (640, 487))
>>> file = open('first_list.txt')
>>> str_first =
>>> import re
>>> str_first = re.sub('\n', '', str_first)
>>> first_list = str_first.split(",")
>>> flx = first_list[0::2]
>>> fly = first_list[1::2]
>>> file2 = open("second_list.txt")
>>> str_sec =
>>> str_sec = re.sub('\n', '', str_sec)
>>> second_list = str_sec.split(",")
>>> slx = second_list[0::2]
>>> sly = second_list[1::2]
>>> im ='RGB', (640, 487))
>>> for i in range(len(flx)):
...     im.putpixel((int(flx[i]), int(fly[i])), (255, 0, 0))
...     i = i + 1
>>> i = 0
>>> for i in range(len(slx)):
...     im.putpixel((int(slx[i]), int(sly[i])), (255, 0, 0))
...     i = i + 1

Automation- Python to the rescue

Automation, let’s accept it, it is not easy, either it is a product line or getting your code built on the click of a button or as we have all done at some point of time, manually changing those  long and long repeated lines of code and hoping that a robot will do it for you(or maybe that rookie intern ;)).

So, talking in terms of code, what actually is automation and how useful it is and what kind of tools does it use. To analyse all this, let me talk about a scenario(read mundane) that recently occurred during my day job which rather forced me to come up with a small ‘robot’. As the client would have it, While writing an objective-c client for a server, I had some java code lying around, which I was referring to and this Java code had a rather long list(~300) of enums(string based) and as we all know c does not support those string based pixies and would need to be stripped away. So, I was wondering that how can I just copy these into a .m file and quickly get away with it. After pondering for like 5 mins, I realized, that it would be better if I could just write some code which can edit my code and hence save me some time.

Having decided so, I picked up Python as the tool to work with and after 15 or so mins(Sorry, my bad, my Python is really lousy, since I mostly read about it but never practice it, but am sure it won’t be so after this post.), came up with this little piece on terminal:

f = open("xyz.h", 'r')
lines = f.readlines()
f = open("xyz.h", 'w')
import re
for line in lines: p = re.compile('\((.*?)\)'); line = p.sub('', line); f.write(line);

AND, voila, I had a file but this time with only enum constants(Before: ENUM_CONSTANTS(“string”) After: ENUM_CONSTANTS). The little robot just accomplished this in few lines code.

Now, I’m looking forward to use Python as much as possible to create little robots like these to edit my code so that I can create a few more bugs in the meantime 😉

Happy Coding.