Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for ADFGVX Cipher by martin_b
from itertools import zip_longest as zipl
T = 'ADFGVX'
def encode(message, alphabet, keyword):
# normalize message
message = [c.lower() for c in message if c.isalnum()]
# get rid of duplicate characters in the keyword
keyword = dict.fromkeys(keyword)
# substitute
t = [T[i] for i in sum([divmod(alphabet.find(c), 6) for c in message], ())]
# create columns
cols = zipl(*[t[i:i + len(keyword)]
for i in range(0, len(t), len(keyword))], fillvalue='')
# match them with keyword letters
for k in keyword:
keyword[k] = next(cols)
# transpose and return result
return "".join(sum([keyword[k] for k in sorted(keyword)], ()))
def decode(message, alphabet, keyword):
# get rid of duplicate characters in the keyword
keyword = dict.fromkeys(keyword)
l = list(keyword)
d, m = divmod(len(message), len(l))
# assign columns to keyword characters
for k in sorted(l):
i = d + (1 if l.index(k) < m else 0)
keyword[k] = message[:i]
message = message[i:]
# transpose (dict keeps order)
t = iter(sum(zipl(*[keyword[k] for k in keyword], fillvalue=''), ()))
# create tuples row-col, substitute and return result
return "".join([alphabet[6 * T.find(x) + T.find(y)] for x, y in zip(t, t) if x != ''])
Nov. 1, 2017