Functions and Classes in Python

Solutions

In [20]:
def encode(message):
    morse = []
    for letter in message:
        morse.append( letter_to_morse[letter.lower()] )
    return morse
In [21]:
encode(message) == morse
Out[21]:
True
In [22]:
encode("Hello World")
Out[22]:
['....', '.', '.-..', '.-..', '---', '/', '.--', '---', '.-.', '.-..', '-..']

In [23]:
morse_to_letter = {}
for letter in letter_to_morse.keys():
    morse_to_letter[ letter_to_morse[letter] ] = letter    
In [24]:
def decode(morse):
    english = []
    for code in morse:
        english.append( morse_to_letter[code] )
    return "".join(english)
In [25]:
decode(morse)
Out[25]:
'sos we have hit an iceberg and need help quickly'

3

In [26]:
for message in messages:
    print("checking for message '%s'..." % message)
    print( message == decode( encode(message) ) )
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-26-63398adc5898> in <module>
----> 1 for message in messages:
      2     print("checking for message '%s'..." % message)
      3     print( message == decode( encode(message) ) )
NameError: name 'messages' is not defined
In [27]:
for message in messages:
    print("checking for message '%s'..." % message)
    print( message.lower() == decode(encode(message)) )
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-27-637c5861e8e5> in <module>
----> 1 for message in messages:
      2     print("checking for message '%s'..." % message)
      3     print( message.lower() == decode(encode(message)) )
NameError: name 'messages' is not defined