Wednesday, May 21, 2014

Decode challenges from the Python Challenge

There is a fun website for Python beginners. Python Challenge. I will post some code I used to solve the problems.

0. 2 to the power of 38.

1. Translate the string by replace every letter with letter position 2 after. Notice the 'z' should translates to 'b'.
text = "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."
result = '';
for c in text:
    if 'a' <= c <= 'z':
        result += chr((ord(c) - ord('a') + 2) % 26 + ord('a'))
    elif 'A' <= c <= 'Z':
        result += chr((ord(c) - ord('A') + 2) % 26 + ord('A'))
    else:
        result += c
print result

2. Find the hidden word from string
text='.. text from html source..'
chList = {}
for ch in text:
    if ch in chList.keys():
        chList[ch] = chList[ch] + 1
    else:
        chList[ch] = 1

print chList #a,e,i,l,q,u,t,y = 1

for ch in text:
    if ch in 'aeilquty':
        print ch #equality

3. Find the hidden word by using regex


text='.. text from html source..'

pattern = "[a-z][A-Z]{3}[a-z][A-Z]{3}[a-z]"

m = re.findall(pattern, text)
result = ""
for str in m:
    result += str[4]
print result


4. Send http request and parse the returning string

import urllib2
import re


link = urllib2.urlopen("http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345")
while link.getcode() == 200:
    #get another nothing code
    text = link.read()

    print text

    pattern = "the next nothing is [0-9]+"

    m = re.search(pattern,text)
    if m:

        tmp = m.group()

        pattern2 = "[0-9]+"

        m = re.search(pattern2, tmp)

        code = m.group()

    else:
        code = str(int(code) / 2)

    url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=" + code

    link = urllib2.urlopen(url)

5. 'Peak Hell' implies 'pickle', format the string, you will see the result

from __future__ import print_function
import pickle
import urllib2
import sys

text = urllib2.urlopen("http://www.pythonchallenge.com/pc/def/banner.p").read()

result = pickle.loads(text)



for arr in result:
    for tuple in arr:
        print(tuple[0]*tuple[1], end='')
    print('\n') 

No comments:

Post a Comment