Last active
August 29, 2015 14:16
-
-
Save le717/5e4e8465973e6fe56173 to your computer and use it in GitHub Desktop.
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
class SOPOMessages: | |
def __init__(self): | |
self.__encodeLegend = {} | |
self.__decodeLegend = {} | |
# Only decode the legends once per instance | |
# We only need to check if the encoding legend is generated | |
# for both legends are generated at the same time | |
if len(self.__encodeLegend) == 0: | |
self.__makeLegends() | |
def __makeLegends(self): | |
key = "A=G B=L C=Q D=V E=A F=D G=H H=M I=R J=W K=B L=E M=I N=S O=N P=X Q=C R=F S=J T=O U=T V=Y W=K X=P Y=Z Z=U".lower().split(" ") | |
# Generate the legend | |
for i in key: | |
code = i.split("=") | |
self.__encodeLegend[code[0]] = code[1] | |
self.__decodeLegend[code[1]] = code[0] | |
def __preserveCase(self, char, newChar): | |
if char.isupper(): | |
return newChar.upper() | |
return newChar | |
def decodeMessage(self, msg): | |
decoded = [] | |
for char in msg: | |
lowerChar = char.lower() | |
# This is not a defined key | |
if lowerChar not in self.__decodeLegend.keys(): | |
decoded.append(char) | |
# This is a defined key | |
else: | |
secretChar = self.__decodeLegend[lowerChar] | |
decoded.append(self.__preserveCase(char, secretChar)) | |
return "".join(decoded) | |
def encodeMessage(self, msg): | |
encoded = [] | |
for char in msg: | |
lowerChar = char.lower() | |
# This is not a defined key | |
if lowerChar not in self.__encodeLegend.keys(): | |
encoded.append(char) | |
# This is a defined key | |
else: | |
secretChar = self.__encodeLegend[lowerChar] | |
encoded.append(self.__preserveCase(char, secretChar)) | |
return "".join(encoded) | |
reader = SOPOMessages() | |
decoded = reader.decodeMessage("OMAFA ZG HN!!!") | |
print(decoded) | |
encoded = reader.encodeMessage("Oh really now?") | |
print(encoded) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment