Skip to content

Instantly share code, notes, and snippets.

@rmkraus
Created August 18, 2015 06:31
Show Gist options
  • Save rmkraus/f245f0663ca25b4c18f3 to your computer and use it in GitHub Desktop.
Save rmkraus/f245f0663ca25b4c18f3 to your computer and use it in GitHub Desktop.
Morse Code Encoder and Decoder
""" Morse Code translator """
MORSE = ['..-', '---', '....', '.--', '.---', '-', '--.-', '-..', '...',
'-..-', '--', '-.', '.-..', '.-', '-.-', '..', '--..', '-.-.', '.--.',
'--.', '-...', '-..--', '.', '.-.', '..-.', '...-', '/', ' ']
ALPHA = ['u', 'o', 'h', 'w', 'j', 't', 'q', 'd', 's', 'x', 'm', 'n', 'l', 'a',
'k', 'i', 'z', 'c', 'p', 'g', 'b', 'y', 'e', 'r', 'f', 'v', ' ', '']
def translate(lkp, out, encoded, in_delim, out_delim):
"""
Translate string from one alphabet to another.
Returns string with message decoded to the output alphabet
lkp: List of the lookup alphabet
out: List of the output alphabet
encoded: Message encoded in lkp alphabet
in_delim: Delimiter used in encoded string to separate letters
out_delim: Delimiter used in decoded string to separate letters
"""
# format input string
encoded = encoded.lower()
if in_delim:
encoded = encoded.split(in_delim)
# translate from one alphabet to another
try:
encoded = [out[lkp.index(letter)] for letter in encoded]
except ValueError:
return None
else:
# combine characters with specified output delimiter
return out_delim.join(encoded)
def main():
""" Gather and direct input/output """
print('\nMorse Code Encoder and Decoder')
print('\t1) Alpha to Morse')
print('\t2) Morse to Alpha')
print('\t3) Quit')
print('')
while True:
cmd = input('> ')
if cmd == "1":
encoded = input('Alpha String: ')
decoded = translate(ALPHA, MORSE, encoded, '', ' ')
if encoded:
print(decoded)
else:
print('Invalid characters.')
elif cmd == "2":
encoded = input('Morse String: ')
decoded = translate(MORSE, ALPHA, encoded, ' ', '')
if decoded:
print(decoded)
else:
print('Invalid characters.')
elif cmd == "3":
print('Goodbye.')
break
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment