-1

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?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Rembit39
  • 19
  • 2
  • May be you can check this link here https://www.geeksforgeeks.org/morse-code-translator-python/ which you can leverage for understanding – Siva Karthikeyan Jan 12 '20 at 22:29

2 Answers2

2

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
0

You have a dictionary with the Key as the letter and the code as the value.

Python dictionaries are lookup by key not value(Unfortunately), BUT there is a way around this as you probably found. Pull the dictionary into items for letter and code like you were doing, BUT put the code to lookup in the first FOR loop. :)

def morse_decrypt(message):
    global morse_dict
    msgList = message.split(" ")
    msgEnglish = ""
    for codeLookup in msgList:
        for letter, code in morse_dict.items():
            if(code == codeLookup):
                msgEnglish += letter
    return msgEnglish


print(morse_decrypt('... --- ...'))

references: Get key by value in dictionary https://www.w3schools.com/python/python_dictionaries.asp

John B
  • 120
  • 1
  • 9