-
Notifications
You must be signed in to change notification settings - Fork 472
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Created a morse code decoder and encoder dealing with corner cases as…
… well
- Loading branch information
1 parent
f610475
commit 0cd53f1
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
|