James PK's Technical Journal

[ Home | Journal ]

Mon, 21 Sep 2015

Python Challenge - Zero to Six

The Python Challenge is a website that sets a number of programming challenges to solve with Python. Each challenge/question has its own URL, the answer to which then forms part of another URL. After successfully answering a question you can access a wiki page where people offer their solutions. To see the solutions to the previous level, replace pc with pcc, i.e. go to: http://www.pythonchallenge.com/pcc/def/ocr.html. Some challenges involve more than one solution.

There are probably any number of ways to solve these, here is my initial pass through the challenges/questions 0 through to 5. With some challenges its a case of trial and error.

Challenge 0 - http://www.pythonchallenge.com/pc/def/0.html

Image shows 2^38.

Answer 274877906944, visit www.pythonchallenge.com/pc/def/274877906944.html

#challenge 0

Challenge 1 - http://www.pythonchallenge.com/pc/def/map.html

We see image of note book

So, given the input i, transform to output o. The input i, is "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."

Hint see the title of the web page 'What about making trans?'. maketrans is a string method, from documentation 'Return a translation table suitable for passing to translate(), that will map each character in from into the character at the same position in to;"

"solution is i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url"

The solution is jvvr://yyy.ravjqpejcnngpig.eqo/re/fgh/ocr.jvon

Answer - ocr

#!/usr/bin/env python
#challenge 1
import string


to_convert="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"

def t(s):
	if s in alpha:
		return alpha[(alpha.index(s)+2)] if idx <=23 else alpha[(idx+1)-25] 
		return s
print "".join(out)

Challenge 2 - http://www.pythonchallenge.com/pc/def/ocr.html

The page states: "recognize the characters. maybe they are in the book, but MAYBE they are in the page source."

Viewing the page source:

"find rare characters in the mess below:"

Lots of characters....apart from letters of the alphabet. Search for those letters, using the re (regular expression) module.

Answer 2 - equality

#!/usr/bin/env python
#challenge 2

import urllib2,re

text = urllib2.urlopen(url)
print "result:","".join(re.findall('[a-z]',contents[idx:]))

Challenge 3 http://www.pythonchallenge.com/pc/def/equality.html

"One small letter, surrounded by EXACTLY three big bodyguards on each of its sides. " Hint is also in the page title "re" a trick regular expression.

Answer 3 - linkedlist

#!/usr/bin/env python
#challenge 3
import urllib2,re

text = urllib2.urlopen(url)

#"One small letter, surrounded by EXACTLY three big bodyguards on each of its
print "".join(re.findall('[a-z][A-Z][A-Z][A-Z]([a-z])[A-Z][A-Z][A-Z][a-z]',contents))

Challenge 4 http://www.pythonchallenge.com/pc/def/linkedlist.html

Page shows "linkedlist.php", so try it. Page source:
<-- urllib may help. DON'T TRY ALL NOTHINGS, since it will never 
end. 400 times is more than enough. -->
A link points to "linkedlist.php?nothing=12345" So we need to loop of 400 attempts to 1)get a url 2)look for the next number in the html 3) that number is the new argument for the next url. But there are some one to watch out for, example http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=82682 Contents
 There maybe misleading numbers in the 
text. One example is 82683. Look only for the next nothing and the next nothing is 63579.

Answer - peak

#!/usr/bin/env python
#challenge 4
import urllib2,re

for i in range(0,400):
    text = urllib2.urlopen(base_url+str(idx))
    print "Contents:",contents
    res=re.search('and the next nothing is ',contents)
    if res:
        print "Stopping"

Challenge 5 http://www.pythonchallenge.com/pc/def/peak.html

The page title is 'peak hell' and the page contents say 'pronounce it'. If you pronounce it does sound like 'pickle', the Python module for serializing and de-serializing a Python object structure. In the html source we see
We need to unpack the contents of banner.p With the following snippet....
import pickle
pkl_file = open('banner.p', 'rb')
data = pickle.load(pkl_file)
print data
...we see the following output.
jamespk@sal:~/code/challenge/5$ python 5.py 
[(' ', 95)]
[(' ', 14), ('#', 5), (' ', 70), ('#', 5), (' ', 1)]

But what to do with the output? The answer is the hint in the file name 'banner'. Banner is program that outputs a large ASCII art version of the text that is supplied to it as its argument. So if we take the second line of output, we should display 14 * ' ', followed by 5 * '#', followed by 70 * ' ', etc,etc.

Answer - channel

#!/usr/bin/env python
#challenge 5

import pickle

pkl_file = open('banner.p', 'rb')
data = pickle.load(pkl_file)
for i in data:
	for j in i:
		str += j[0] * j[1]
	print str

posted at: 00:00 | path: /python | permanent link to this entry

Sun, 20 Oct 2013

Python - Displaying numeric data returned from functions using Matplotlib

"Understanding Algorithms and Data Structures" by Brunskill and Turner was on the reading list of one the units on my CS course. It has some interesting exercises. Page 21 (in the chapter "Necessary Mathematics") has an exercise on sketching and comparing graphs for various mathematical functions. I thought I'd have a go at it with Python and Matplotlib (a Python library for graphs).

Using a combination of range and map (which applies a function to every item of an iterable), keeps the code fairly succinct:

#!/usr/bin/env python
import matplotlib.pyplot as plt 
import math_functions as mf 



for i in functions:
 plt.plot(range(5), map(i,range(1,6)), 'o-', label=i.__name__)
 print i.__name__,map(i,range(1,6)) 

plt.legend(loc='upper left')
ax.set_title("Excercises 2.1")

Image output:

posted at: 00:00 | path: /python | permanent link to this entry

Made with Pyblosxom