Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
dict.fromkeys solution in Clear category for Playfair Cipher by David_Jones
def create_table_from(key):
letters, digits = set('abcdefghijklmnopqrstuvwxyz'), set('0123456789')
key_symbols = {}.fromkeys(key).keys()
key = ''.join(list(key_symbols) + sorted(letters - key_symbols)
+ sorted(digits - key_symbols))
return [key[6*i:6*(i+1)] for i in range(6)]
def get_diagraphs_from(message):
diagraphs = []
message = ''.join(ch for ch in message.lower() if ch.isalnum())
i = 0
while i < len(message):
diagraph = message[i:i+2]
if i == len(message) - 1:
return diagraphs + [diagraph + 'zx'[diagraph == 'z']]
if message[i] == message[i+1]:
diagraph = message[i] + 'xz'[message[i] == 'x']
i += 1
else:
i += 2
diagraphs.append(diagraph)
return diagraphs
def find_coordinates(key_table, ch):
for i in range(6):
for j in range(6):
if key_table[i][j] == ch:
return i, j
def encode(message, key):
key_table = create_table_from(key)
diagraphs = get_diagraphs_from(message)
for i in range(len(diagraphs)):
x1, y1 = find_coordinates(key_table, diagraphs[i][0])
x2, y2 = find_coordinates(key_table, diagraphs[i][1])
if x1 == x2:
diagraphs[i] = key_table[x1][(y1+1)%6] + key_table[x2][(y2+1)%6]
elif y1 == y2:
diagraphs[i] = key_table[(x1+1)%6][y1] + key_table[(x2+1)%6][y2]
else:
diagraphs[i] = key_table[x1][y2] + key_table[x2][y1]
return ''.join(diagraphs)
def decode(secret_message, key):
key_table = create_table_from(key)
diagraphs = get_diagraphs_from(secret_message)
for i in range(len(diagraphs)):
x1, y1 = find_coordinates(key_table, diagraphs[i][0])
x2, y2 = find_coordinates(key_table, diagraphs[i][1])
if x1 == x2:
diagraphs[i] = key_table[x1][(y1+5)%6] + key_table[x2][(y2+5)%6]
elif y1 == y2:
diagraphs[i] = key_table[(x1+5)%6][y1] + key_table[(x2+5)%6][y2]
else:
diagraphs[i] = key_table[x1][y2] + key_table[x2][y1]
return ''.join(diagraphs)
May 19, 2019