Last active
December 25, 2015 22:29
-
-
Save Natim/7049927 to your computer and use it in GitHub Desktop.
Python2 and Python3 compatible carre de 25 encoder and decoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import print_function | |
from six.moves import input, xrange, map | |
from string import ascii_letters | |
alphabet = "ABCDEFGHIJKLMNOPQRSTUVXYZ" | |
def get_maps(keyword): | |
keyword = keyword.upper().replace('W', 'V') | |
keyword = [c for c in keyword if c in ascii_letters] | |
maps = [] | |
for c in keyword + list(alphabet): | |
if c not in maps: | |
maps.append(c) | |
return maps | |
def show_maps(maps): | |
for i in xrange(5): | |
print('\n+---+---+---+---+---+') | |
print('|', end='') | |
for j in xrange(5): | |
print(' %c |' % maps[i*5+j], end='') | |
print('\n+---+---+---+---+---+\n') | |
class Encoder(object): | |
def __init__(self, maps): | |
self.maps = maps | |
def encode(self, duo): | |
if len(duo) < 2: | |
return duo | |
first_pos = self.maps.index(duo[0]) | |
second_pos = self.maps.index(duo[1]) | |
# Swap columns | |
encoded_fpos = (int(first_pos / 5), second_pos % 5) | |
encoded_spos = (int(second_pos / 5), first_pos % 5) | |
# change the other coordinate if columns are both the same | |
if first_pos % 5 == second_pos % 5: | |
encoded_fpos = (int(second_pos / 5), first_pos % 5) | |
encoded_spos = (int(first_pos / 5), second_pos % 5) | |
# Get the encoded letter from coordinates | |
encoded_duo = (self.maps[encoded_fpos[0] * 5 + encoded_fpos[1]], | |
self.maps[encoded_spos[0] * 5 + encoded_spos[1]]) | |
return encoded_duo | |
def transpose(text, maps): | |
# Remove all whitespaces and capitalize | |
text = text.upper().replace('W', 'V') | |
text_ascii = [c for c in text if c in ascii_letters] | |
# Build letter couples | |
size = len(text_ascii) | |
duos = [text_ascii[i:i+2] for i in range(0, size, 2)] | |
# Generate for each duo its encoded_duo | |
encoder = Encoder(maps) | |
encoded_duos = map(encoder.encode, duos) | |
return ''.join([''.join(x) for x in encoded_duos]) | |
def main(): | |
keyword = input('Enter the keyword: ') | |
maps = get_maps(keyword) | |
assert len(maps) == 25 | |
show_maps(maps) | |
text_to_transpose = input('Enter text:\n') | |
print(transpose(text_to_transpose, maps)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment