From 0cd53f1bd0ea2cda3404f7dd0b06ae30c8451417 Mon Sep 17 00:00:00 2001 From: Rohit Sharma Date: Mon, 7 Oct 2024 10:24:53 +0530 Subject: [PATCH] Created a morse code decoder and encoder dealing with corner cases as well --- morse_code_decoder_encoder.py | 62 +++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 morse_code_decoder_encoder.py diff --git a/morse_code_decoder_encoder.py b/morse_code_decoder_encoder.py new file mode 100644 index 0000000..9460b48 --- /dev/null +++ b/morse_code_decoder_encoder.py @@ -0,0 +1,62 @@ +MORSE_CODE_DICT = { 'A':'.-', 'B':'-...', + 'C':'-.-.', 'D':'-..', 'E':'.', + 'F':'..-.', 'G':'--.', 'H':'....', + 'I':'..', 'J':'.---', 'K':'-.-', + 'L':'.-..', 'M':'--', 'N':'-.', + 'O':'---', 'P':'.--.', 'Q':'--.-', + 'R':'.-.', 'S':'...', 'T':'-', + 'U':'..-', 'V':'...-', 'W':'.--', + 'X':'-..-', 'Y':'-.--', 'Z':'--..', + '1':'.----', '2':'..---', '3':'...--', + '4':'....-', '5':'.....', '6':'-....', + '7':'--...', '8':'---..', '9':'----.', + '0':'-----', ', ':'--..--', '.':'.-.-.-', + '?':'..--..', '/':'-..-.', '-':'-....-', + '(':'-.--.', ')':'-.--.-'} + +def encrypt(message): + """Encrypt the message to Morse code.""" + cipher = '' + for letter in message: + if letter in MORSE_CODE_DICT: # Check if letter is valid + cipher += MORSE_CODE_DICT[letter] + ' ' + else: + print(f'This: {letter} could not be converted into Morse code, removing it from the message') + return cipher.strip() # Remove trailing space + +def decrypt(message): + message += ' ' + + decipher = '' + citext = '' + for letter in message: + if (letter != ' '): + i = 0 + citext += letter + else: + i += 1 + if i == 2 : + decipher += ' ' + else: + decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT + .values()).index(citext)] + citext = '' + + return decipher +switch = input("Enter 1 for encryption and 2 for decryption: ") +if switch == '1': + message = input("Enter the message you want to encrypt(press enter for default input): ") + if not message: + print("No inputs detected so we are using default input 'Rohit'") + message = 'Rohit' + result = encrypt(message.upper()) + print (result) + +else: + message = input("Enter the message you want to decrypt(press enter for default message): ") + if not message: + print("No inputs detected so we are using default input '.--. -.-- - .... --- -.'") + message = '.--. -.-- - .... --- -.' + result = decrypt(message) + print (result) + \ No newline at end of file