Skip to content

Instantly share code, notes, and snippets.

@lainq
Last active June 28, 2021 15:36
Show Gist options
  • Save lainq/948633e7be432965d3b7857a6eeedc27 to your computer and use it in GitHub Desktop.
Save lainq/948633e7be432965d3b7857a6eeedc27 to your computer and use it in GitHub Desktop.
An encoder that I made
import string
import sys
class Encoder(object):
__characters = string.printable
class __EncoderError(Exception):
def __init__(self, text, allowed_characters):
message_string = (
f"{text}:Characters should be included in {allowed_characters}"
)
super().__init__(message_string)
def __init__(self, text):
self.text = text
if not Encoder.check_is_valid_string(self.text, self.__characters):
raise self.__EncoderError(self.text, self.__characters)
def encode(self):
ascii_values = [
f"{round(value)}-"
for value in [(ord(character) * 10) / 2 for character in self.text]
]
encoded_string = "".join(ascii_values)[:-1]
return encoded_string
@staticmethod
def check_is_valid_string(text, __characters):
characters = [current_char for current_char in text]
is_valid = [(character in __characters) for character in characters]
return False not in is_valid
class Decoder(object):
def __init__(self, encoded_string):
self.encoded_string = encoded_string
if not Encoder.check_is_valid_string(self.encoded_string, string.printable):
raise Exception("Characters should be printable")
def decode(self):
number_values = list(
map(lambda element: int(element), self.encoded_string.split("-"))
)
return "".join([chr(round((value * 2) / 10)) for value in number_values])
def encode(text):
try:
return Encoder(text).encode()
except Exception as encoder_exception:
print(encoder_exception.__str__())
def decode(encoded_string):
try:
return Decoder(encoded_string).decode()
except Exception as decoder_error:
print(decoder_error.__str__())
def main():
actions = {"encode": encode, "decode": decode}
arguments = sys.argv[1:]
if len(arguments) == 0:
return None
action = arguments[0]
if action not in actions:
raise Exception(f"Invalid argument: {action}")
execute_function = actions.get(action)
input_data = input("Data >>>").strip()
if execute_function:
return execute_function(input_data)
results = main()
print(results if results else "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment