python challenge 12 解题总结

python challenge 12网址:www.pythonchallenge.com/pc/return/evil.html 

本来以为这个谜题又是与图片打交道,实际则不是。但是查看源代码以及改变一些URL来检查,没有什么进展,于是稍微搜索一下网上的提示:

页面源码中,图片的名称是evil1.jpg,于是把URL地址改为evil2.jpg,打开一个画面,显示not jpg -- .gfx,URL继续改为evil2.gfx,把这个文件下载下来。按照页面上发牌的图片找出提示:以发牌的形式分成5份。 另外,读取图片时需要使用2进制的方式读取。 源代码如下:

f = open('evil2.gfx', 'rb')  
data = f.read()  
for i in range(5):
    file = open('evil_%d.jpg' % i, 'wb')
    file.write(data[i::5])
    file.close()  
f.close() 

 

下一关:www.pythonchallenge.com/pc/return/disproportional.html

 

需要的用户名密码为:huge(用户名),file(密码)

阅读全文 »

python challenge 13解题总结

python challenge 13 网址:www.pythonchallenge.com/pc/return/disproportional.html

打开网页的源码能够看到<area shape="circle" coords="326,177,45" href="../phonebook.php" />这条信息,于是打开网页www.pythonchallenge.com/pc/phonebook.php,显示如下信息:

<methodResponse><fault><value><struct><member><name>faultCode</name><value><int>105</int></value></member><member><name>faultString</name><value><string>XML error: Invalid document end at line 1, column 1</string></value></member></struct></value></fault></methodResponse>

这里就想到了python的模块xmlrpclib,于是就用

test=xmlrpclib.ServerProxy('http://www.pythonchallenge.com/pc/phonebook.php')

以及print test.system.listMethods()发现了有phote的方法,于是就得出答案了,源代码如下:

test = xmlrpclib.ServerProxy("http://www.pythonchallenge.com/pc/phonebook.php")
ret = test.phone('Bert')   #这里的Bert是上一关的提示信息
print ret

下一关的网址:www.pythonchallenge.com/pc/return/italy.html

 

需要的用户名密码为:huge(用户名),file(密码)

阅读全文 »

python challenge 14解题总结

python challenge 14网址:www.pythonchallenge.com/pc/return/italy.html

根据网页标题的提示:walk around,网页代码的提示:100*100 = (100+99+99+98) + (…,还有那张螺旋状的面包图片,猜测,要把下面那张图(其实这个图是10000*1的,居然能显示成方的)以这种形式展开:

import PIL.Image
def nextpoint(direction,oldpoint):
        if direction==0:
            return oldpoint+1
        elif direction==1:
            return oldpoint+100
        elif direction==2:
            return oldpoint-1
        elif direction==3:
            return oldpoint-100
        else:
            print 'wrong!'
im=PIL.Image.open('wire.png')
newim=PIL.Image.new(im.mode,[100,100])
context=list(im.getdata())
result=[1]*10000
result[0:100]=context[0:100]
p=100
i=1
nextp=0
oldpoint=99
for v in range(99,0,-1):
        for q in range(v,0,-1):
                nextp=nextpoint(i,oldpoint)
                result[nextp]=context[p]
                p=1+p
                oldpoint=nextp
        i=(i+1)%4
        for q in range(v,0,-1):
                nextp=nextpoint(i,oldpoint)
                result[nextp]=context[p]
                p=1+p
                oldpoint=nextp
        i=(i+1)%4        
newim.putdata(result)
newim.save('w2.png')


下一关地址:www.pythonchallenge.com/pc/return/cat.html 页面显示uzi,于是输入网址:www.pythonchallenge.com/pc/return/uzi.html

需要的用户名密码为:huge(用户名),file(密码)

阅读全文 »

python challenge 15解题总结

python challenge 15网址:www.pythonchallenge.com/pc/return/uzi.html

 其实题目的主要意思就是:1**6年 Jan 26的后一天,猜猜这是谁的生日?用google搜搜吧

代码:

import calendar   
print [i for i in range(1006, 2006, 10) if calendar.weekday(i, 1, 1) == 3][-3]  

下一关的网址:www.pythonchallenge.com/pc/return/mozart.html

 

需要的用户名密码为:huge(用户名),file(密码)

阅读全文 »

python challenge 16解题总结

 

python challenge 16网址:www.pythonchallenge.com/pc/return/mozart.html


打开页面源码发现一句提示:let me get this straight,提示说把它弄直,图片里面杂乱无章的点很明显有很多是品红色的短线,把图按行平移,使得红线对齐。

源代码为:

import Image, ImageChops    
image = Image.open("mozart.gif")  
magic = chr(195)  
for y in range(image.size[1]):  
     box = 0, y, image.size[0], y + 1  
     row = image.crop(box)  
     bytes = row.tostring()  
     i = bytes.index(magic)  
     row = ImageChops.offset(row, -i)  
     image.paste(row, box)  
image.save("new.gif")  


于是下一关的网页为:www.pythonchallenge.com/pc/return/romance.html

阅读全文 »

python challenge 17解题总结

 

python challenge 17网址:www.pythonchallenge.com/pc/return/romance.html

这道谜题比较复杂,需要结合前面几个题一起来解,需要python的re, urllib, urllib2, bz2, xmlrpclib  这些模块,首先利用 urllib, urllib2去请求URL,获取一些数据,接着利用bz2模块对数据进行处理,。。。

源代码如下:

import re, urllib, urllib2, bz2, xmlrpclib  
  
# First of all, get the data that is hidden within the "Set-Cookie" headers:  
  
uri = "http://www.pythonchallenge.com/pc/def/linkedlist.php?busynothing=%s"  
nn_rep = re.compile("the next busynothing is (d+)")  
cookie_val = re.compile("info=([^;]+);")  
result = []  
n = "12345"  
  
while True:  
    h = urllib.urlopen(uri % n)  
    next = h.read()  
    cookie = h.info().getheader("Set-Cookie")  
    h.close()  
  
    cval = cookie_val.search(cookie)  
  
    if cookie and cval:  
        result.append(urllib.unquote_plus(cval.group(1)))  
  
    try:  
        n = nn_rep.search(next).group(1)  
    except:  
        break  
  
print bz2.decompress("".join(result)  
  
# Get Leopold's phone numer using the code for level 13:  
  
conn = xmlrpclib.ServerProxy("http://www.pythonchallenge.com/pc/phonebook.php")  
  
print conn.phone("Leopold")  
  
# Now phone Mozart's father and tell him that "the flowers are on their way":  
  
uri = "http://www.pythonchallenge.com/pc/stuff/violin.php"  
msg = "the flowers are on their way"  
req = urllib2.Request(  
    uri, headers = { "Cookie": "info=" + urllib.quote_plus(msg)}  
)  

下一关网址为:www.pythonchallenge.com/pc/return/balloons.html

阅读全文 »

python challenge 18解题总结

 

python challenge 18的网址是:www.pythonchallenge.com/pc/return/balloons.html,打开网页后会出现如下的图片,并且网页源代码会给出提示:can you tell the difference? 仔细对比两个图片会发现这两个图片的亮度显然不同,于是打开www.pythonchallenge.com/pc/return/brightness.html,再仔细看网页源代码,结果发现另外一个提示:maybe consider deltas.gz,于是把deltas.gz给下载下来(www.pythonchallenge.com/pc/return/deltas.gz)。

 

分析下载下来的文件的源代码:

import gzip, difflib  
   
h = gzip.open("deltas.gz")  
d = difflib.Differ()  
  
part_1, part_2 = [], []  
file_1, file_2, file_3 = [], [], []  
  
for line in h:  
    part_1.append(line[0:53])  
    part_2.append(line[56:-1])  
  
h.close()  
  
for line in list(d.compare(part_1, part_2)):  
    if line[0] == "+":  
        file_1.append(line[2:])  
    elif line[0] == "-":  
        file_2.append(line[2:])  
    else:  
        file_3.append(line[2:])  
  
for n, data in enumerate((file_1, file_2, file_3)):  
    temp = []  
  
    for line in data:  
        temp.extend([chr(int(o, 16)) for o in line.strip().split(" ") if o])  
  
    h = open("%s.png" % (n + 1), "wb")  
    h.writelines(temp)  
    h.close()  
print urllib2.urlopen(req).read()  

下一关的网址:www.pythonchallenge.com/pc/hex/bin.html(用户名:butter 密码:fly)

阅读全文 »

python challenge 19解题总结

 python challenge 19网址:www.pythonchallenge.com/pc/hex/bin.html(用户名:butter,密码是fly)。打开网页后出现下面的图片,仔细打开源代码会发现:

一个电子邮件,下载后能弄出音乐,听到sorry。图中显示的印度地图颜色是反的,联想到反转。

除了文件头之外的都前后字节交换,从新的音乐听到idiot,然后过去……

源代码如下:

import base64, wave, array
 
# Input ...
 
h = open("data")
 
a = array.array("c", base64.b64decode(h.read())) a.byteswap() h.close()
 
# ... Processing ...
 
h = wave.open("modified.wav", "wb")
 
h.setnchannels(1) h.setsampwidth(1) h.setframerate(22050)
 
# ... Output h.writeframes(a.tostring()) h.close()

 

 

下一关网址:www.pythonchallenge.com/pc/hex/idiot.html

阅读全文 »

Python实现简单的遗传算法

硕士毕业论文的时候使用了遗传算法,所以研究了一段时间,曾经用 Python 写一个简单的遗传算法,好自己拿来实验。整个代码还是仿照《游戏编程中的人工智能技术》中的代码来写的。如果想简单的学习一下遗传算法以及简单应用《游戏编程中的人工智能技术》是不错的选择。 代码如下面所附。 我写了一个简单的测试函数 main 运行后多数情况下会产生如下输出 ----------------- Function: y = 0 - 2 * x * x + 12 * x + 5 The best genome is: [0, 0, 1, 1] The variable is: 3 The max value is 23 ----------------- Function: y = 0 - 2 * x * x + 8 * x + 4 The best genome is: [0, 0, 1, 0] The variable is: 2 The max value is 12 ----------------- 以 y = 0 - 2 * x * x + 8 * x + 4 为例,在 Matlab 中画出该函数的曲线的时候,可以看到 该函数的极值点确实在 x = 2 处,证明算法还是相当成功的。 因为写的测试算法主要针对求函数的极大值,如果是求函数极小值可以乘上 -1 就 OK 了。 其实上边的函数,乘上 -1 ,然后求导也可以知道极值为 x=8/4=2 ,这是极小值,乘上 -1 就得极大值了。 算是初步改写成功了,当然还有很多问题,比如选择时用的轮盘赌,但是 AI 的书上的算法似乎有点问题,另外似乎变异操作也有点问题,变异我现在只是变异一处,而原书上则是每一处都根据变异率来进行变异。 种群要设置的稍微大点,太小了没效果。变异率也要大一点。 另外,测试函数里的解空间比较小,还有就是终止条件目前仅判断代数是否超过了设置的最大代数,我想还应该在判断适应性分数最高的地方设置终止条件。这样就避免了多余的运算 [code lang="python"] # -*- coding:utf-8 -*- # file: GA.py # date: 2011-10-22 # note: import random class genome: def __init__(self, length = 0): self.fitness = 0 self.bits = [] for i in range(length): self.bits.append(random.randint(0, 1)) class ga: def __init__(self, pop_size, genome_len, expr = 'y = 0 - 2 * x * x + 8 * x + 4', crossover_rate = 0.7, mutation_rate = 0.01, max_generation = 1000 ): self.crossover_rate = crossover_rate self.mutation_rate = mutation_rate self.pop_size = pop_size self.genome_len = genome_len self.generation = 0 self.genomes = [] self.busy = False self.fittest_genome = genome() self.best_fitness_score = 0 self.total_fitness_score = 0 self.expr = expr self.max_generation = max_generation def create_start_populations(self): del self.genomes[0:] for i in range(self.pop_size): self.genomes.append(genome(self.genome_len)) self.generation = 0 self.best_fitness_score = 0 self.total_fitness_score = 0 def selection(self): f_slice = random.uniform(0, 1) * self.total_fitness_score c_f_slice = 0.0 selected_genome = 0 for i in range(self.pop_size): c_f_slice = c_f_slice + self.genomes[i].fitness if c_f_slice f_slice: selected_genome = i break return self.genomes[i] def crossover(self, mum, dad): baby1 = [] baby2 = [] if (random.uniform(0, 1) self.crossover_rate): baby1 = mum.bits; baby2 = dad.bits; return baby1, baby2 cp = random.randint(0, self.genome_len - 1) for i in range(cp): baby1.append(mum.bits[i]) baby2.append(dad.bits[i]) for i in range(cp, self.genome_len): baby1.append(dad.bits[i]) baby2.append(mum.bits[i]) return baby1, baby2 def mutate(self, bits): if (random.uniform(0, 1) self.mutation_rate): mp = random.randint(0, self.genome_len - 1) bits[mp] = int(not bits[mp]) def decode(self, gen): x = self.bin2int(gen) exec(self.expr) return y def bin2int(self, lists): m = 1 r = 0 lists.reverse() for i in range(len(lists)): r = r + m * lists[i] m = m * 2 lists.reverse() return r def update_fitness_scores(self): self.total_fitness_score = 0 for i in range(self.pop_size): self.genomes[i].fitness = self.decode(self.genomes[i].bits) self.total_fitness_score ...

阅读全文 »

python challenge 20解题总结

 

python challenge 20网址:www.pythonchallenge.com/pc/hex/idiot.html,查看网页源码后,可以看到idiot2.html,于是打开网址:www.pythonchallenge.com/pc/hex/idiot2.html,查看网页的源码就看到了but inspecting it carefully is allowed,于是想到需要用到httplib模块,并且需要用认证的信息,于是源代码如下。

import httplib, base64

base64_login = base64.encodestring('%s:%s' % ("butter", "fly"))[:-1]
headers = {"Authorization": "Basic %s" % base64_login}
conn = httplib.HTTPConnection("www.pythonchallenge.com")

# Needless to say that normally we wouldn't know about the exact byte
# ranges yet and thus probably use infinite loops instead ...

for n in range(30203, 30314):
    headers["Range"] = "bytes=%s-%s" % (n, n + 1)
    conn.request("GET", "/pc/hex/unreal.jpg", "", headers)
    response = conn.getresponse()
    data = response.read()

    if data:
        print data

# We now know that our username is "invader".

for n in (2123456744, 2123456743):
    headers["Range"] = "bytes=%s-%s" % (n, n + 1)
    conn.request("GET", "/pc/hex/unreal.jpg", "", headers)
    response = conn.getresponse()

    print response.read()

# We learned that "the password is your new nickname in reverse", thus:
# "redavni". Further, that "it is hiding at 1152983631".

headers["Range"] = "bytes=1152983631-1152983632"
conn.request("GET", "/pc/hex/unreal.jpg", "", headers)
response = conn.getresponse()

h = open("data.zip", "wb")
h.write(response.read())
h.close()

# Unzip the file and read the "readme.txt" it contains.

阅读全文 »