StevenPZChan
StevenPZChan
3 min read

Categories

Tags

继续挑战


第14题地址italy.html

  • italy.jpg
  • 网页标题是walk around,题目内容是一个小图案wire.png源码中有一行隐藏信息:

    <!– remember: 100*100 = (100+99+99+98) + (… –>

按照提示,题目应该是跟小图案和隐藏信息有关,先把图案搞下来:

from io import BytesIO
import requests
from PIL import Image

with requests.Session() as sess:
    sess.auth = ('huge', 'file')
    response = sess.get('http://www.pythonchallenge.com/pc/return/wire.png').content
    img = Image.open(BytesIO(response))
print(img)
<PIL.PngImagePlugin.PngImageFile image mode=RGB size=10000x1 at 0x7F249FC731D0>

我们可以看到,这个小图案的大小是10000x1

将隐藏信息进行剖析,可以得出,式子是将这10000个像素分成若干组数字的加和。

再结合标题walk around和螺旋形的面包图片联想,这(100+99+99+98)正好是100*100图像的最外圈的像素总和。
题目的意思是让我们将这10000个像素按螺旋形从外到内填充成一张100*100的图像!


不多说,直接开始写算法(假设以左上角开始,顺时针方向,其他方向只是这个结果的旋转和翻转而已):

from enum import Enum, auto

class Direction(Enum):
    Left = auto()
    Right = auto()
    Up = auto()
    Down = auto()
    
limits = {Direction.Left: 0, Direction.Right: 99, Direction.Up: 0, Direction.Down: 99}

x, y = 0, 0
direction = Direction.Right
img_new = Image.new(img.mode, (100, 100))
img_new_data = img_new.load()
for pixel in img.getdata():
    img_new_data[x, y] = pixel
    if direction == Direction.Left:
        if x <= limits[direction]:
            y -= 1
            limits[Direction.Down] = y
            direction = Direction.Up
        else:
            x -= 1
    elif direction == Direction.Right:
        if x >= limits[direction]:
            y += 1
            limits[Direction.Up] = y
            direction = Direction.Down
        else:
            x += 1
    elif direction == Direction.Up:
        if y <= limits[direction]:
            x += 1
            limits[Direction.Left] = x
            direction = Direction.Right
        else:
            y -= 1
    elif direction == Direction.Down:
        if y >= limits[direction]:
            x -= 1
            limits[Direction.Right] = x
            direction = Direction.Left
        else:
            y += 1
img_new

png

结果是一只猫?将地址改为cat.html得到:

and its name is uzi. you’ll hear from him later.

再改为uzi.html,来到了下一题。

总结:还行,就是形象思维和数学的一点点对应,还要实现一点小算法。

本题代码地址14_italy.ipynb