/python/atbash-cipher/atbash_cipher.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
import string
import re

CHUNK_SIZE = 5

# Build translation tables
letters = string.ascii_lowercase
table = string.maketrans(string.ascii_letters, letters[::-1]*2)

# Unencodable characters - will be removed during encoding.
unencodable = string.whitespace + string.punctuation


def decode(text):
    return text.translate(table, ' ')


def encode(text):
    # Get a lower case alphanumeric version of the text
    encoded = text.translate(table, unencodable)

    # Split into chunks
    chunks = [
        encoded[i:i+CHUNK_SIZE]
        for i in xrange(0, len(encoded), CHUNK_SIZE)
    ]
    return ' '.join(chunks)


if __name__ == '__main__':
    contents = open('pg2600.txt').read() * 10
    encoded = encode(contents)

@tstirrat15 thinks this looks great

Comments

Unencodables are part of the translation pass now, removed the regex substitution for significant speed gains.

Replaced range with xrange, which also helped with speed.

helenst commented 31 January 2015 at 08:23 UTC

I like it! I also like that you defined a constant for CHUNK_SIZE, despite that not being a part of the problem definition.

tstirrat15 commented 31 January 2015 at 20:13 UTC

Cool

RryLee commented 22 March 2016 at 10:45 UTC

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