StyleInCode

RSS

 

Alphabet Cipher

1 February 2025

A solution to the Alphabet Cipher Kata described at Awesome Katas.

Solution

""" alphabet_cipher.py """

# usage: python3 alphabet_cipher.py


def repeat(text):
    """ non-ending """
    while True:
        for i in text.lower():
            yield i


def decode(seed, text):
    """ decode text using seed """
    a = ord('a')
    s = repeat(seed)
    output = []
    for i in text.lower():
        if 'a' <= i <= 'z':
            col = next(s)
            j = chr(a + (ord(i) - ord(col)) % 26)
            output.append(j)
    return ''.join(output)


def encode(seed, text):
    """ encode text using seed """
    a = ord('a')
    s = repeat(seed)
    output = []
    for i in text.lower():
        if 'a' <= i <= 'z':
            col = next(s)
            j = chr(a + (ord(col) + ord(i) - 2 * a) % 26)
            output.append(j)
    return ''.join(output)


def decipher(messagetext, ciphertext):
    """ calculate seed """
    def isolate(text):
        """ isolate repeating text """
        for size in range(1, len(text) + 1):
            seed = text[:size]
            checks = [seed.startswith(text[j * size:(j + 1) * size])
                      for j in range(len(text) // len(seed) + 1)]
            if all(checks):
                return seed
        return text

    a = ord('a')
    output = []
    for j, i in enumerate(messagetext.lower()):
        if 'a' <= i <= 'z':
            col = chr((ord(ciphertext[j].lower()) - ord(i)) % 26 + a)
            output.append(col)
    return isolate(''.join(output))


if __name__ == '__main__':
    secret = 'burgertime'
    message = 'Do you have a copy of BurgerTime?'
    answer = encode(secret, message)
    assert answer == 'eipuyytdqedigeswucdkflkoqv'

    secret = 'vigilance'
    message = 'meet me on Tuesday evening at seven'
    answer = encode(secret, message)
    assert answer == 'hmkbxebpxpmyllyrxiiqtoltfgzzv'

    secret = 'burgertime'
    cipher = 'eipuyytdqedigeswucdkflkoqv'
    answer = decode(secret, cipher)
    assert answer == 'doyouhaveacopyofburgertime'

    secret = 'vigilance'
    cipher = 'hmkbxebpxpmyllyrxiiqtoltfgzzv'
    answer = decode(secret, cipher)
    assert answer == 'meetmeontuesdayeveningatseven'

    message = 'thequickbrownfoxjumpsoveralazydog'
    cipher = 'opkyfipmfmwcvqoklyhxywgeecpvhelzg'
    answer = decipher(message, cipher)
    assert answer == 'vigilance'

    message = 'packmyboxwithfivedozenliquorjugs'
    cipher = 'hcqxqqtqljmlzhwiivgbsapaiwcenmyu'
    answer = decipher(message, cipher)
    assert answer == 'scones'

Categories

Links