Search code examples
pythondictionarymorse-code

using loops and dictionaries for decoding a morse code program


I am writing encode and decode functions for morse code. The encode function is working, but the decode function is giving the same output multiple times. Can someone see how i can fix the for loop to only print once. Btw it is printing backwards because I have it printing like that

sample input for decode function

....  .  .-..  .-..  --- 

expected output

HELLO

output

OLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEH

my code

MORSE_CODES={'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 decode_Morse(my_msg): 
 
  string=" "
  
  for morsecode in my_msg:
    wordsplit=my_msg.split()

    for ch in wordsplit:
      if ch!="  ":
        string=string+ list(MORSE_CODES.keys())[list(MORSE_CODES.values()).index(ch)] 
      else:
        ch=" "
      
  return string

def main()
     my_msg_reverse_Morse_plain=decode_Morse(my_msg_reverse_Morse)
     print("Plaintext of the previous Morse Code:",

Solution

  • What about simply this?

    MORSE_DECODES = {v:k for k,v in MORSE_CODES.items()}
    def decode_Morse(my_msg):
        return "".join(MORSE_DECODES[ch] for ch in my_msg.split())
    

    Your own code uses one too many loops, try this:

    def decode_Morse(my_msg): 
     
      string=""
      
      for morsecode in my_msg.split():
          string=string+list(MORSE_CODES.keys())[list(MORSE_CODES.values()).index(morsecode)]
          
      return string
    

    If you have multiple words then you must use a different separator for mere letters and words. For example on space for letters, 3 for words, then this will work:

    def decode_Morse(my_msg): 
      string = ""
      for word in my_msg.split("   "):
          for ch in word.split():
              string=string+list(MORSE_CODES.keys())[list(MORSE_CODES.values()).index(ch)]
          string = string + " "
      return string