Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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("/")])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading