Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
decorators and no table solution in Creative category for Playfair Cipher by maelnor
def prepare_key(f):
def wrapper(message, key):
key = key.lower() + "abcdefghijklmnopqrstuvwxyz0123456789"
_key = []
for l in key:
if l not in _key:
_key.append(l)
if len(_key) == 36:
break
return f(message, _key)
return wrapper
def prepare_message(f):
def wrapper(message, key):
message = list(filter(lambda l: l.isalnum(), message.lower()))
pos = 0
while pos < len(message)-1:
if message[pos] == message[pos+1]:
message.insert(pos+1, 'x' if message[pos] != 'x' else 'z')
pos += 2
if len(message) % 2 == 1:
message.append('z' if message[pos] != 'z' else 'x')
return f(message, key)
return wrapper
def pairs_message(f):
def wrapper(message, key):
return f(zip(message[::2], message[1::2]), key)
return wrapper
def code(pairs, key, decode=False):
mod = -1 if decode else 1
result = ''
cornered = lambda x, y: key[x - x % 6 + y % 6]
hshifted = lambda i: cornered(i, i + mod)
vshifted = lambda i: key[(i + 6 * mod) % 36]
for pair in pairs:
i1 = key.index(pair[0])
i2 = key.index(pair[1])
if i1 // 6 == i2 // 6:
result += hshifted(i1)
result += hshifted(i2)
elif i1 % 6 == i2 % 6:
result += vshifted(i1)
result += vshifted(i2)
else:
result += cornered(i1, i2)
result += cornered(i2, i1)
return result
@prepare_key
@prepare_message
@pairs_message
def encode(message, key):
return code(message, key, False)
@prepare_key
@pairs_message
def decode(message, key):
return code(message, key, True)
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"
Dec. 25, 2014
Comments: