Use a dictionary and print out values when matching keys and vice versa
I have a dictionary where key
is a letter in the alphabet and its value
is its corresponding Morse code letter (e.g. “A":). I
also have a user input and I enter the user into the message there. Once they hit enter, it checks each entered letter to see if it’s Morse code or English letters, by seeing if it’s in a value or key. After that, I want it to print the corresponding letter (e.g. if it finds “.-“, it will print “A”). What should I do?
So far, here’s my code:
translation = {
"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": "--..",
" ": " "
}
user_input = input("Input english or morse code message:\n").upper()
for i in user_input:
if i in translation.keys():
print(translation.values())
if i in translation.values():
print(translation.keys())
Solution
To translate text into Morse code, simply map
the characters of the string to the corresponding value in the translation
dictionary:
>>> msg = "HELLO WORLD"
>>> morse = ' '.join(map(translation.get, msg))
>>> morse
'.... . .-.. .-.. --- .-- --- .-. .-.. -..'
Note that I separated the code with spaces, otherwise it would be almost impossible to decode the message back, as some sequences may produce different combinations of characters. To translate back, you first have to reverse the dictionary; Then split
the Morse message by space and get the value from the inverse dictionary.
>>> trans_back = {v: k for k, v in translation.items()}
>>> ''.join(map(trans_back.get, morse.split()))
'HELLOWORLD'
Note that this removes spaces. To solve this problem, you can use a different symbol than the space to separate the Morse code sequence.
Or with this slightly more complex version, use re.split
to split at one space, provided that space is not followed by it, or there is no other space in front of:
>>> ''.join(map(trans_back.get, re.split("(?<! ) | (?! )", morse)))
'HELLO WORLD'
In order to decide which translation to take, i.e. whether the original text is Morse or plain text, you can check only if the first or all characters of the string are dictionary in translation
, or if they are valid Morse symbols:
if all(c in translation for c in msg):
# translate to morse
elif all(c in ".- " for c in msg):
# translate back
else:
# don't know what to do
Note: This answer is posted before adding trailing spaces to all entries in the dictionary.