PageRenderTime 27ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/junk/python/challenge/common.py

http://pytof.googlecode.com/
Python | 451 lines | 417 code | 4 blank | 30 comment | 2 complexity | b64b29f4c2395079521a001f688f8c57 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, GPL-3.0, GPL-2.0, IPL-1.0
  1. #!/usr/bin/env python
  2. def challengeUrlOpen(url, php = False, deff = False):
  3. import webbrowser
  4. suffix = '.html'
  5. if php: suffix = '.php'
  6. last = 'def'
  7. if deff: last = 'return'
  8. webbrowser.open('http://www.pythonchallenge.com/pc/' + last + '/' + url + suffix)
  9. def level0():
  10. '''
  11. http://www.pythonchallenge.com/pc/def/0.html
  12. The hint is 2^38
  13. '''
  14. a = 2 ** 38
  15. challengeUrlOpen(str(a))
  16. def createTranslationTable():
  17. '''
  18. http://www.pythonchallenge.com/pc/def/map.html
  19. The hint is:
  20. K -> M
  21. O -> E
  22. E -> G
  23. It means we have to translate each letter by letter + 2 using
  24. each letter ascii code
  25. '''
  26. import string
  27. all = string.lowercase
  28. first = ord(all[0])
  29. size = len(all)
  30. newAll = ''
  31. for s in all:
  32. code = ord(s)
  33. letter = chr(code)
  34. newCode = (code - first + 2) % size
  35. newLetter = chr(newCode + first)
  36. newAll += newLetter
  37. table = string.maketrans(all, newAll)
  38. return table
  39. def level1():
  40. encodedStr = \
  41. ''' 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.
  42. '''
  43. table = createTranslationTable()
  44. newStr = encodedStr.translate(table)
  45. print newStr
  46. challengeUrlOpen('map'.translate(table))
  47. def getLastComment(url, serialize = False):
  48. import urllib
  49. fo = urllib.urlopen(url)
  50. text = fo.read()
  51. first = text.rfind('<!--')
  52. last = text.rfind('-->')
  53. mess = text[first+len('<!--\n'):last-1]
  54. if serialize:
  55. from tempfile import mkstemp
  56. import os
  57. (fd, name) = mkstemp()
  58. print name
  59. fo = os.fdopen(fd, 'w')
  60. fo.write(mess)
  61. fo.close()
  62. return mess
  63. def level2():
  64. '''
  65. http://www.pythonchallenge.com/pc/def/ocr.html
  66. recognize the characters. maybe they are in the book,
  67. but MAYBE they are in the page source.
  68. You have to fetch the html page. Within it you have two comments,
  69. the first is:
  70. find rare characters in the mess below:
  71. the second is a mess of character. Both are the last comment of the document
  72. '''
  73. urlBase = 'http://www.pythonchallenge.com/pc/def/ocr.html'
  74. mess = getLastComment(urlBase)
  75. assert mess[0] == '%'
  76. assert mess[-1] == '*'
  77. import string
  78. url = ''
  79. for c in mess:
  80. if c in string.lowercase: url += c
  81. # rare characters (using the lowercase filter, or using a dict and counting occurences)
  82. # form the word 'equality'
  83. challengeUrlOpen(url)
  84. def level3():
  85. '''
  86. http://www.pythonchallenge.com/pc/def/equality.html'
  87. One small letter, surrounded by EXACTLY three big bodyguards on each of its sides.
  88. We still have to parse the last piece of data at the end
  89. '''
  90. urlBase = 'http://www.pythonchallenge.com/pc/def/equality.html'
  91. mess = getLastComment(urlBase, True)
  92. import string
  93. Up = string.uppercase
  94. Low = string.lowercase
  95. candidates = []
  96. url = ''
  97. for c in range(len(mess)):
  98. if c+7 >= len(mess): continue
  99. i,j,k,L,m,n,o = mess[c:c+7]
  100. if i in Up and j in Up and k in Up and L in Low and m in Up and n in Up and o in Up:
  101. candidates.append(c)
  102. for c in candidates:
  103. if mess[c-1] in Low and mess[c+7] in Low:
  104. url += mess[c+3]
  105. challengeUrlOpen(url, True)
  106. class foo(Exception): pass
  107. def nextNothingLevel4(id):
  108. import webbrowser
  109. from urllib import urlencode, urlopen
  110. url = urlencode([('nothing', str(id))])
  111. fo = urlopen('http://www.pythonchallenge.com/pc/def/linkedlist.php?' + url)
  112. line = fo.read()
  113. last = line.split()[-1]
  114. if not last.isdigit():
  115. print line
  116. raise foo
  117. else:
  118. return int(last)
  119. def level4():
  120. '''
  121. http://www.pythonchallenge.com/pc/def/linkedlist.php
  122. if we click on the pictures, which is at linkedlist.php?nothing=12345", we get a 92512
  123. <!-- urllib may help. DON'T TRY ALL NOTHINGS, since it will never
  124. end. 400 times is more than enough. -->
  125. After a while, the php print peak.html ...
  126. '''
  127. i = 12345
  128. while True:
  129. try:
  130. i = nextNothing(i)
  131. except foo:
  132. i /= 2
  133. def level5():
  134. '''
  135. http://www.pythonchallenge.com/pc/def/peak.html
  136. The hint is: pronounce it
  137. In the web page there is a something to download: banner.p.
  138. And there's also: <!-- peak hell sounds familiar ? -->
  139. If you say it loud you get pickle...
  140. '''
  141. from urllib import urlencode, urlopen
  142. fo = urlopen('http://www.pythonchallenge.com/pc/def/banner.p')
  143. text = fo.read()
  144. import pickle
  145. object = pickle.loads(text)
  146. for t in object:
  147. line = ''
  148. for elem in t:
  149. i, j = elem
  150. for k in xrange(j):
  151. line += i
  152. print line
  153. def level6():
  154. '''
  155. http://www.pythonchallenge.com/pc/def/channel.html
  156. '''
  157. from urllib import urlencode, urlopen, urlretrieve
  158. from zipfile import ZipFile
  159. urlBase = 'http://www.pythonchallenge.com/pc/def/channel.zip'
  160. import tempfile
  161. tempFile = tempfile.mktemp()
  162. fo = urlretrieve(urlBase, tempFile)
  163. zi = ZipFile(tempFile)
  164. print zi.read('readme.txt') # here they tell us to start with 90052
  165. comments = {}
  166. import string
  167. Up = string.uppercase
  168. class fooException(Exception): pass
  169. def nextNothing(id, zi, url):
  170. line = zi.read(str(id) + '.txt')
  171. infos = zi.getinfo(str(id) + '.txt')
  172. if infos.comment in Up:
  173. if not infos.comment in url or not url:
  174. url += infos.comment
  175. last = line.split()[-1]
  176. if last.isdigit():
  177. return last, url
  178. else:
  179. raise fooException
  180. i = 90052 # first start with me
  181. url = ''
  182. while True:
  183. try:
  184. i, url = nextNothing(i, zi, url)
  185. except(fooException):
  186. challengeUrlOpen(url.lower())
  187. return
  188. def level7():
  189. '''
  190. http://www.pythonchallenge.com/pc/def/oxygen.html
  191. '''
  192. from urllib import urlencode, urlopen, urlretrieve
  193. from zipfile import ZipFile
  194. urlBase = 'http://www.pythonchallenge.com/pc/def/oxygen.png'
  195. import tempfile
  196. tempFile = tempfile.mktemp()
  197. fo = urlretrieve(urlBase, tempFile)
  198. #print tempFile
  199. import Image
  200. #photo = Image.open(tempFile)
  201. #photo = Image.open('/home/bsergean/Pictures/oxygen_greyscale.png')
  202. photo = Image.open('level7.png')
  203. photo.load()
  204. pixels = list(photo.getdata())
  205. colors = {}
  206. line = []
  207. c = 1
  208. p_prev = pixels[0]
  209. startGrey = False
  210. for i, p in enumerate(pixels):
  211. #if i > 659 * 50 and i < 659 * 51:
  212. #print p #line.append(p)
  213. if p == p_prev:
  214. c += 1
  215. else:
  216. if c == 5:
  217. if startGrey:
  218. break
  219. else:
  220. startGrey = True
  221. if startGrey:
  222. if c >= 14:
  223. line.append(p)
  224. line.append(p)
  225. elif c >= 5:
  226. line.append(p)
  227. c = 1
  228. p_prev = p
  229. mySet = set()
  230. sentence = []
  231. for l in line:
  232. if l[0:2] == l[1:3]:
  233. sentence.append( chr(l[1]) )
  234. mySet.add(l[0])
  235. print mySet
  236. print ''.join(sentence)
  237. print ''.join([chr(i) for i in [105, 100, 166, 101, 103, 144, 105, 166, 121]])
  238. def level8_write_module(ascii_bin):
  239. tempfile = 'mymodule.py'
  240. fo = open(tempfile, 'a')
  241. fo.write(ascii_bin + '\n')
  242. fo.close()
  243. def level8_read_values():
  244. from mymodule import un, pw
  245. from bz2 import decompress
  246. print decompress(un)
  247. print decompress(pw)
  248. def level8():
  249. '''
  250. http://www.pythonchallenge.com/pc/def/integrity.html
  251. '''
  252. from urllib import urlencode, urlopen
  253. fo = urlopen('http://www.pythonchallenge.com/pc/def/integrity.html')
  254. lines = fo.read().splitlines()
  255. for l in lines:
  256. if l.strip().startswith('coords'):
  257. coords = l.split('=')[1].replace('"', '').split(',')
  258. if l.strip().startswith('un'):
  259. un = l.replace(':', '=')
  260. level8_write_module(un)
  261. if l.strip().startswith('pw'):
  262. pw = l.replace(':', '=')
  263. level8_write_module(pw)
  264. level8_read_values()
  265. # Draw a horse
  266. import Image, ImageDraw
  267. coords = [int(i) for i in coords]
  268. X = max(coords)
  269. Y = X
  270. white = (255, 255, 255)
  271. blue = (0, 0, 255)
  272. photo = Image.new('RGB', (X, Y), white)
  273. draw = ImageDraw.Draw(photo)
  274. draw.line(coords, blue)
  275. import sys
  276. #photo.save('/Users/100drine/Desktop/foo8.png', "PNG")
  277. photo.save('level8.png', "PNG")
  278. def level9():
  279. '''
  280. http://www.pythonchallenge.com/pc/return/good.html
  281. '''
  282. import urllib2
  283. # Create an OpenerDirector with support for Basic HTTP Authentication...
  284. auth_handler = urllib2.HTTPBasicAuthHandler()
  285. auth_handler.add_password('realm', 'host', 'huge', 'file')
  286. opener = urllib2.build_opener(auth_handler)
  287. # ...and install it globally so it can be used with urlopen.
  288. urllib2.install_opener(opener)
  289. # Authentication does not work (real and host should be replaced by the
  290. # right value)
  291. #urllib2.urlopen('http://www.pythonchallenge.com/pc/return/good.html')
  292. from urllib import urlencode, urlopen
  293. fo = urlopen('http://www.pythonchallenge.com/pc/return/good.html')
  294. lines = fo.read().splitlines()
  295. i = 0
  296. while i < len(lines):
  297. line = lines[i]
  298. i += 1
  299. if line.strip().startswith('first:'):
  300. line = lines[i] # Useless ?
  301. first = ''
  302. while len(line):
  303. line = lines[i]
  304. i += 1
  305. first += line
  306. if line.strip().startswith('second:'):
  307. second = ''
  308. while len(line):
  309. line = lines[i]
  310. i += 1
  311. second += line
  312. first = [int(i) for i in first.split(',')]
  313. second = [int(i) for i in second.split(',')]
  314. # first is a cow / second looks like a penis ? -> bull
  315. import Image, ImageDraw
  316. coords = second
  317. X = max(coords)
  318. Y = X
  319. white = (255, 255, 255)
  320. blue = (0, 0, 255)
  321. photo = Image.new('RGB', (X, Y), white)
  322. draw = ImageDraw.Draw(photo)
  323. draw.line(first, blue)
  324. draw.line(second, blue)
  325. import sys
  326. #photo.save('/Users/100drine/Desktop/foo9.png', "PNG")
  327. photo.save('level9.png', "PNG")
  328. def level10():
  329. '''
  330. http://www.pythonchallenge.com/pc/return/bull.html
  331. len(a[30])= ?
  332. There is a bull picture, when you click it you get a text file
  333. with this sequence in it ...
  334. a = [1, 11, 21, 1211, 111221,
  335. '''
  336. def a(n):
  337. dict = {}
  338. res = ''
  339. for e in n:
  340. if e in dict:
  341. dict[e] += 1
  342. else:
  343. if dict != {}:
  344. elem = dict.keys()[0]
  345. occurences = dict.values()[0]
  346. res += str(occurences)
  347. res += elem
  348. dict = {}
  349. dict[e] = 1
  350. if dict != {}:
  351. elem = dict.keys()[0]
  352. occurences = dict.values()[0]
  353. res += str(occurences)
  354. res += elem
  355. return res
  356. N = a('1')
  357. i = 1
  358. while i <= 30:
  359. print i, len(N)
  360. N = a(N)
  361. i += 1
  362. challengeUrlOpen('5808', False, True)
  363. def level11():
  364. '''
  365. http://www.pythonchallenge.com/pc/return/5808.html
  366. Odd even.
  367. The image is like a big chess board with color variations.
  368. '''
  369. import Image
  370. photo = Image.open('cave_level11.jpg')
  371. photo.load()
  372. w, h = photo.size
  373. pixels = list(photo.getdata())
  374. white = (255, 255, 255)
  375. hidden_image = Image.new('RGB', (w/2, h), white)
  376. seq = []
  377. for i,p in enumerate(pixels):
  378. if i % 2 != 0:
  379. seq.append(p)
  380. new_seq = []
  381. for j in xrange(h):
  382. if j % 2 != 0:
  383. new_seq.extend(seq[j*w/2:(j+1)*w/2])
  384. hidden_image.putdata(new_seq)
  385. hidden_image.save('cave_subpicture.png')
  386. # we can read 'evil' in this captcha !
  387. return
  388. def level12():
  389. '''
  390. http://www.pythonchallenge.com/pc/return/evil.html
  391. dealing evil. Nothing but a picture
  392. '''
  393. level11()