Python/ciphers/morse_code_implementation.py

98 lines
1.8 KiB
Python
Raw Normal View History

# Python program to implement Morse Code Translator
# Dictionary representing the morse code chart
2019-10-05 05:14:13 +00:00
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": "-----",
"&": ".-...",
"@": ".--.-.",
":": "---...",
",": "--..--",
2019-10-05 05:14:13 +00:00
".": ".-.-.-",
"'": ".----.",
'"': ".-..-.",
2019-10-05 05:14:13 +00:00
"?": "..--..",
"/": "-..-.",
"=": "-...-",
"+": ".-.-.",
2019-10-05 05:14:13 +00:00
"-": "-....-",
"(": "-.--.",
")": "-.--.-",
# Exclamation mark is not in ITU-R recommendation
"!": "-.-.--",
2019-10-05 05:14:13 +00:00
}
def encrypt(message: str) -> str:
2019-10-05 05:14:13 +00:00
cipher = ""
for letter in message:
2019-10-05 05:14:13 +00:00
if letter != " ":
cipher += MORSE_CODE_DICT[letter] + " "
else:
cipher += "/ "
# Remove trailing space added on line 64
return cipher[:-1]
def decrypt(message: str) -> str:
2019-10-05 05:14:13 +00:00
decipher = ""
letters = message.split(" ")
for letter in letters:
if letter != "/":
decipher += list(MORSE_CODE_DICT.keys())[
list(MORSE_CODE_DICT.values()).index(letter)
]
else:
decipher += " "
return decipher
def main() -> None:
message = "Morse code here"
result = encrypt(message.upper())
print(result)
message = result
result = decrypt(message)
print(result)
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
main()