Morse code to alphanumeric (python)
Question: I need to write a program that can encode/decode messages using morse code.

To encode a message, the program needs to read an input file containing the
alphanumeric characters then output the corresponding Morse encoded message.

To decode a message, the program will read a file with the Morse code then
output the alphanumeric characters.

This is what I have so far but I can't get it to decode correctly:

    
    
    import string
    
    def to_from(text, dict_in):
        for i in text:
            if i.upper() in dict_in:
                print "%6s" % (dict_in[i]),
            else:
                print i, "not in dictionary"
        print
    
    letters = {'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': '----*' 
            }
    
    frommorse = dict((b,a) for a,b in letters.items())
    text = raw_input('What is the translation you need?\n')
    text=text.strip()
    
    if text[0] in string.letters:
        to_from(text, letters)
    else:
        to_from(text, frommorse)
    

When I tried decoding *-, it would print "E T" instead of A. What am I doing
wrong?


Answer: For encoding a string to morse code try this

    
    
     APNU = {'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': '----.' 
            }
    
    
    string = 'yourstring'
    for char in string:
        print APNU[char.upper()]
    

or

    
    
    [APNU[char.upper()] for char in string]
    

