crypto_square.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from itertools import zip_longest
import math
import re


def transpose(square):
    """
    Transpose a list of strings (e.g. ["ab", "cd"] -> ["ac", "bd"]
    """
    return [
        ''.join(filter(None, chars))
        for chars in zip_longest(*square)
    ]


def chunkify(text, chunk_size):
    """
    Break text into chunks of a given size, or less for the final chunk
    """
    return [
        text[i:i+chunk_size]
        for i in range(0, len(text), chunk_size)
    ]


def squarify(text):
    """
    Arrange text into a square, using next largest square number as a guide
    """
    if text:
        sqrt = math.sqrt(len(text))
        return chunkify(text, math.ceil(sqrt))
    return [text]


def encode(text):
    """
    Cipher square encode the given text
    """
    stripped = re.sub(r"[^\w]", '', text.lower())
    square = squarify(stripped)
    return ' '.join(transpose(square))

Comments


You're not logged in right now. Please login via GitHub to comment