I started to translate Morse code to English and there is an issue. Here is my code:
morse_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': '--..',
}
def morse_decrypt(message):
m1 = message.split()
new_str = []
letter = ''
for i,n in morse_dict.items():
if n in m1:
letter = str(i)
new_str.append(letter)
return ''.join(new_str)
print(morse_decrypt('... --- ...'))
>>>os
But when I try to use function it prints each character one time. I don't know what the problem. What I am doing wrong?
Your morse_dict
translates alphabetical letters into Morse code letters. But you want the reverse since you're trying to decrypt rather than encrypt. Either rewrite your dictionary or use
morse_to_alpha = dict(map(reversed, morse_dict.items()))
to flip the key-value pairs.
Once you've done that, then you can look up each message chunk in the translation dictionary (rather than the other way around):
def morse_decrypt(message):
morse_to_alpha = dict(map(reversed, morse_dict.items()))
return "".join(map(morse_to_alpha.get, message.split()))
This still breaks encapsulation. morse_to_alpha
should be made into a parameter so you're not accessing global state, and it's wasteful to flip the dict for every translation. I'll leave these adjustments for you to handle.
It's also unclear how to handle errors; this raises a (not particularly clearly named) exception if the Morse code is invalid.