Search code examples
pythonloopsdictionaryif-statementmorse-code

why are the spaces in between the words not showing up


I have a morse program but the spaces in between the words are not showing does any one have any ideas? Prefer the simplest way to do so

sample input:

APRIL FOOLS DAY

output for encode_Morse function:

' .-  .--.  .-.  ..  .-..     ..-.  ---  ---  .-..  ...     -..  .-  -.-- '

output for the decode_Morse function:

APRILFOOLSDAY

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':' --.. '}

##Define functions here
def encode_Morse(my_msg):
  #my_msg=my_msg.upper()

  my_msg_Morse=""
  for letter in my_msg:
    
    if letter!=" " and letter not in MORSE_CODES:
      my_msg_Morse+="*"
    elif letter!=" ":
       my_msg_Morse+= MORSE_CODES[letter]
    else:
      my_msg_Morse+="   "

  return my_msg_Morse+""


def decode_Morse(my_msg): 
 
  string=""
  
  for word in my_msg.split("     "):
  
    for ch in word.split():
      if ch!="  " and ch!="*":
        string=string + list(MORSE_CODES.keys())[list(MORSE_CODES.values()).index(" "+ch+" ")]
      elif ch=="     ":
        string+=" "
    string=string+"" 

  return string

Solution

  • The split function absorbes your delimiter

    I propose :

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