I only get one word as output using dictionaries while it should be two

I made a function which converts morse code to text using dictionaries. The slash ‘/’ is the equivalent of a whitespace and splits two words. I therefore made a list using the strip function. I also used a loop to convert each element of that list into text but without success.

dicti = {'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': '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '.': '.-.-.-', ',': '--..--', '?': '..--..', '-': '-....-', '/': '-..-.', ':': '---...', "'": '.----.', ')': '-.--.-', ';': '-.-.-', '(': '-.--.', '=': '-...-', '@': '.--.-.'}

decode = {v: k for k, v in dicti.items()}

def morse_to_text(morse):
    l = morse.split("/")
    for element in l:
        new_element = element.split()
        result = "".join(decode[symbol] for symbol in new_element)
        return result

print(morse_to_text('... --- .../.--. .. . -'))

This function doesn’t give me the right output. It should give me ‘SOS PIET’ but it only gives me ‘SOS’. I tried putting the return assignment outside the loop but the output only changed to the second word: ‘PIET’. Is someone willing to explain how to fix this problem? Thanks in advance.

>Solution :

You return in the middle of the loop and exit the function. Fixed:

def morse_to_text(morse):
    l = morse.split("/")
    results = []
    for element in l:
        new_element = element.split()
        result = "".join(decode[symbol] for symbol in new_element)
        results.append(result)
    return " ".join(results)

You can also turn it into a reasonably understable one-liner:

def morse_to_text(morse):
    return " ".join(["".join(decode[symbol] for symbol in word.split())
                     for word in morse.split("/")])

Leave a Reply