def advance_rewind_and_extract(img_url, pwd, size):
    """Finds the correct range start and use the password to ultimately extract
    and display next mission's content"""
    msg = read_riddle(img_url, range_header(size)).strip()
    msg = read_riddle(img_url, range_header(size - len(msg) - 2)).strip()
    start = msg.rstrip(".").rsplit(maxsplit=1)[-1]
    zip_content = read_url(img_url, range_header(start)).strip()
    with ZipFile(BytesIO(zip_content), "r") as zip_file:
        readme, package = zip_file.namelist()
        print(zip_file.read(readme, pwd=pwd.encode()).decode())
        print(zip_file.extract(package, pwd=pwd.encode()))
Beispiel #2
0
def unravel_riddle(msg, new_url):
    """Uses `message` as cookie to finally unravel the riddle at `new_url`"""
    cookie = f"""info={msg.split('"', 2)[1].replace(" ", "+")}"""
    riddle = read_riddle(new_url, headers={"Cookie": cookie})
    for line in (line.lstrip() for line in riddle.splitlines()):
        if not line.startswith("<"):
            return line.rsplit(maxsplit=1)[-1].split(".", 1)[0]
def solve_puzzle(puzzle_url):
    """Solves puzzle in `puzzle_url` and return all possible solutions"""
    puzzle = read_riddle(puzzle_url)
    horizontal, vertical = load_puzzle(puzzle)
    assert len(horizontal) == len(vertical)
    rows_vars, cols_vars = gen_vars(len(horizontal))
    return [
        sat_ip_to_text(ip, rows_vars)
        for ip in satisfy_all(rows_vars, cols_vars, horizontal, vertical)
    ]
def unravel_riddle(url, cache):
    """Follows the riddle leads until the end to ultimately unravel it"""
    curr = 12345
    while True:
        try:
            if curr not in cache:
                cache[curr] = read_riddle(f"{url}?nothing={curr}")
            riddle = cache[curr]
        except KeyboardInterrupt:
            exit(0)
        except Exception as e:
            print(f"Bang! {e} ({curr})")
            exit(1)
        try:
            next_ = int(riddle.rsplit(maxsplit=1)[-1])
        except ValueError:
            if riddle == "Yes. Divide by two and keep going.":
                next_ = curr // 2
            else:
                return riddle
        curr = next_
# https://opensource.org/licenses/BSD-3-Clause
# Copyright (c) 2018-2020, Pablo S. Blum de Aguiar <*****@*****.**>

# http://www.pythonchallenge.com/pc/return/bull.html

from auth import read_riddle


def look_and_say(digits):
    """Describes a digit as in a look-and-say manner"""
    desc = [1, digits[0]]
    for digit in digits[1:]:
        if desc[-1] == digit:
            desc[-2] += 1
        else:
            desc.extend([1, digit])
    return desc


def look_and_say_nth(n):
    """Generates the nth element of the look-and-say sequence"""
    digits = [1]
    for _ in range(n):
        digits = look_and_say(digits)
    return digits


url = "http://www.pythonchallenge.com/pc/return/bull.html"
n = int(read_riddle(url).rsplit("[", 1)[1].split("]", 1)[0])
print(len(look_and_say_nth(n)))
Beispiel #6
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# This file is part of Python Challenge Solutions
# https://github.com/scorphus/PythonChallengeSolutions

# Licensed under the BSD-3-Clause license:
# https://opensource.org/licenses/BSD-3-Clause
# Copyright (c) 2018-2020, Pablo S. Blum de Aguiar <*****@*****.**>

# http://www.pythonchallenge.com/pc/ring/guido.html

from auth import read_riddle
from bz2 import decompress

riddle = read_riddle("http://www.pythonchallenge.com/pc/ring/guido.html")
data = bytes(len(line) for line in riddle.splitlines() if "<" not in line)
print(decompress(data).decode().rstrip("!").rsplit(maxsplit=1)[-1])
Beispiel #7
0
    new_image = Image.new(image.mode, (100, 100))
    for pixel in reversed(image.getdata()):
        if -50 < x <= 50 and -50 < y <= 50:
            new_image.putpixel((x + 49, 50 - y), pixel)
        if x == y or x < 0 and x == -y or x > 0 and x == 1 - y:
            dx, dy = -dy, dx
        x, y = x + dx, y + dy
    return new_image


class CatNameSayer(HTMLParser):
    """Parses an HTML and display data for <b> tags"""
    def handle_starttag(self, tag, _):
        self.show = tag == "b"

    def handle_data(self, data):
        if self.show:
            print(data)
        self.show = False


url = "http://www.pythonchallenge.com/pc/return/italy.html"
image_content = read_url(get_last_src_url(url))
image = Image.open(BytesIO(image_content))

spiral_and_transform(image).save("14-italy.png", "PNG")
print("Open 14-italy.png only to see a cat")

cat = read_riddle(url.replace("italy", "cat"))
CatNameSayer().feed(cat)
Beispiel #8
0
def discover_next_url(url):
    """Retrieves the riddle URL sitting at `url` — 🤷"""
    url_base = url.rsplit("/", 1)[0]
    new_path = read_riddle(url).rstrip("\n.").rsplit(maxsplit=1)[-1]
    return f"{url_base}/{new_path}"
def extract_image(zip_data):
    """Extracts an image from a corrupt zip file inside `zip_data`"""
    patch_update_crc()
    with zipfile.ZipFile(BytesIO(zip_data)) as outer:
        for name in outer.namelist():
            try:
                with zipfile.ZipFile(outer.open(name)) as inner, inner.open(
                    inner.namelist()[0]
                ) as img_file:
                    # Pillow couldn't read the corrupt gif, even with
                    # PIL.ImageFile.LOAD_TRUNCATED_IMAGES set to True
                    return WandImage(file=img_file)
            except (zipfile.BadZipFile, WandBaseError):
                pass


ambiguity_data = get_ambiguity_data()
image = extract_image(ambiguity_data)
image_data = image.export_pixels()
pil_image = Image.frombytes("RGBA", image.size, bytes(image_data))
print(image_to_text(pil_image, skip=3))

for line in read_riddle(
    "http://www.pythonchallenge.com/pc/hex/decent.html"
).splitlines():
    if not line:
        break
    if "<" in line:
        continue
    print(line.rsplit(maxsplit=1)[-1])
@cached
def unravel_riddle(url, cache):
    """Follows the riddle leads until the end to ultimately unravel it"""
    curr = 12345
    while True:
        try:
            if curr not in cache:
                cache[curr] = read_riddle(f"{url}?nothing={curr}")
            riddle = cache[curr]
        except KeyboardInterrupt:
            exit(0)
        except Exception as e:
            print(f"Bang! {e} ({curr})")
            exit(1)
        try:
            next_ = int(riddle.rsplit(maxsplit=1)[-1])
        except ValueError:
            if riddle == "Yes. Divide by two and keep going.":
                next_ = curr // 2
            else:
                return riddle
        curr = next_


url = "http://www.pythonchallenge.com/pc/def/linkedlist.html"
url_base = url.rsplit("/", 1)[0]
new_path = read_riddle(url).rstrip()

if __name__ == "__main__":
    print(unravel_riddle(f"{url_base}/{new_path}"))

@autocached
def solve_puzzle(puzzle_url):
    """Solves puzzle in `puzzle_url` and return all possible solutions"""
    puzzle = read_riddle(puzzle_url)
    horizontal, vertical = load_puzzle(puzzle)
    assert len(horizontal) == len(vertical)
    rows_vars, cols_vars = gen_vars(len(horizontal))
    return [
        sat_ip_to_text(ip, rows_vars)
        for ip in satisfy_all(rows_vars, cols_vars, horizontal, vertical)
    ]


url = "http://www.pythonchallenge.com/pc/rock/arecibo.html"
puzzle_path = get_nth_comment(url, 2).rsplit(maxsplit=1)[-1]
url_base = url.rsplit("/", 1)[0]
puzzle_url = f"{url_base}/{puzzle_path}"
print("\n".join(solve_puzzle(puzzle_url)))

url = "http://www.pythonchallenge.com/pc/rock/up.html"
puzzle_url = get_last_href_url(url)
print("\n".join(solve_puzzle(puzzle_url)))

url = "http://www.pythonchallenge.com/pc/rock/python.html"
for line in read_riddle(url).splitlines():
    if "<" not in line:
        print(line.strip())
        break
def read_csv_cells(url):
    """Reads the cells of the CSV mentioned in the riddle"""
    csv_url = get_last_src_url(url).replace("jpg", "csv")
    rows = (line.rstrip(",").split(", ")
            for line in read_riddle(csv_url).splitlines())
    return list(chain.from_iterable(rows))