-2

This program prints English to morse code and then I am trying to reverse the morse code in the main program below. I have provided a sample input with outputs that I get and I expect. Basically, I do not want each ./- to be reversed, I just need the last morse character to be the first, 4th to be the 2nd, etc.

normal morse output:     ....    .    .-..    .-..    ---
reverse output I get:    ---    ..-.    ..-.    .    .... 
expected output reverse: ---    .-..    .-..    .    ....
def encodeChartoMorse(text_input):
      all_caps=text_input.upper()
      length=len(all_caps)
      string=''
      for letter in range(0, length):
        char = all_caps[letter]
        
    
        if (char == "A"):
          char= ".-"
        elif (char == "B"):
          char= "-..."
        elif (char== "C"):
          char= "-.-."
        elif (char == "D"):
          char= "-.."
        elif (char == "E"):
          char= "."
        elif (char == "F"):
          char= "..-."
        elif (char == "G"):
          char= "--."
        elif (char == "H"):
          char= "...."
        elif (char == "I"):
          char= ".."
        elif (char == "J"):
          char= ".---"
        elif (char == "K"):
          char= "-.-"
        elif (char == "L"):
          char= ".-.."
        elif (char == "M"):
          char= "--"
        elif (char == "N"):
          char= "-."
        elif (char == "O"):
          char= "---"
        elif (char == "P"):
          char= ".--."
        elif (char == "Q"):
          char= " --.-" 
        elif (char == "R"):
          char= ".-."
        elif (char == "S"):
          char= "..."
        elif (char == "T"):
          char= "-" 
        elif (char == "U"):
          char= "..-" 
        elif (char == "V"):
          char= "...-"
        elif (char == "W"):
          char= ".--"
        elif (char == "X"):
          char= "-..-"
        elif (char == "Y"):
          char= "-.--"
        elif (char == "Z"):
          char= "--.."
        else:
          char= '*'
        string=string + '    ' + char
    
      return string
    
    def main():
      ##Put your main program here
      text_input=str(input("Enter some text to convert to Morse code: "))
      print (text_input.upper())
      
     
      morse_code=encodeChartoMorse(text_input)
      print(morse_code)
    
      rev_morse=morse_code[::-1]
      print(rev_morse)
    main()
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
wiskah
  • 11
  • 3

1 Answers1

2

To reverse each block (i.e. character) of your output you can str.split on whitespace to get morse characters, then reverse that list, and then str.join with whitespace again.

def reverse_morse(text):
    return ' '.join(text.split()[::-1])

>>> reverse_morse('.... . .-.. .-.. ---')
'--- .-.. .-.. . ....'
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218