Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
divmod found! solution in Clear category for Playfair Cipher by CDG.Axel
from string import ascii_lowercase as lt, digits as dg
from functools import partial
def playfair(message, key, m):
key, shift = list(dict.fromkeys(key + lt + dg)), lambda x: (x + m) % 6
message, res = list(filter(str.isalnum, message.lower())), ''
while message:
a = message.pop(0)
b = (message.pop(0) if message[0] != a else 'xz'[a == 'x']) if message else 'zx'[a == 'z']
(ad, am), (bd, bm) = [divmod(key.index(x), 6) for x in (a, b)]
if am == bm: ad, bd = map(shift, [ad, bd])
else: am, bm = map(shift, [am, bm]) if ad == bd else (bm, am)
res += key[ad * 6 + am] + key[bd * 6 + bm]
return res
encode, decode = partial(playfair, m=1), partial(playfair, m=-1)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert encode("Fizz Buzz is x89 XX.", "checkio101") == 'do2y7mt22kry94y2y2', "Encode fizz buzz"
assert decode("do2y7mt22kry94y2y2", "checkio101") == 'fizxzbuzzisx89xzxz', "Decode fizz buzz"
assert encode("How are you?", "hello") == 'ea2imb1ht0', "Encode How are you"
assert decode("ea2imb1ht0", "hello") == 'howareyouz', "Decode How are you"
assert encode("My name is Alex!!!", "alexander") == 'i1dlkxjqlexn', "Encode Alex"
assert decode("i1dlkxjqlexn", "alexander") == 'mynameisalex', "Decode Alex"
assert encode("Who are you?", "human") == 'rnvftc1jd5', "Encode WHo"
assert decode("rnvftc1jd5", "human") == 'whoareyouz', "Decode Who"
assert encode("ATTACK AT DAWN", "general") == 'ewwektewhnua', "Encode attack"
assert decode("ewwektewhnua", "general") == 'attackatdawn', "Decode attack"
Nov. 25, 2021
Comments: