Skip to content

Instantly share code, notes, and snippets.

@ajgappmark
Forked from ebuckley/gist:1842461
Created March 6, 2016 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajgappmark/afbca177d1087013873c to your computer and use it in GitHub Desktop.
Save ajgappmark/afbca177d1087013873c to your computer and use it in GitHub Desktop.
python code to encode/decode morse code
morseAlphabet ={
"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" : "--..",
" " : "/"
}
inverseMorseAlphabet=dict((v,k) for (k,v) in morseAlphabet.items())
testCode = ".... . .-.. .-.. --- / -.. .- .. .-.. -.-- / .--. .-. --- --. .-. .- -- -- . .-. / --. --- --- -.. / .-.. ..- -.-. -.- / --- -. / - .... . / -.-. .... .- .-.. .-.. . -. --. . ... / - --- -.. .- -.-- "
# parse a morse code string positionInString is the starting point for decoding
def decodeMorse(code, positionInString = 0):
if positionInString < len(code):
morseLetter = ""
for key,char in enumerate(code[positionInString:]):
if char == " ":
positionInString = key + positionInString + 1
letter = inverseMorseAlphabet[morseLetter]
return letter + decodeMorse(code, positionInString)
else:
morseLetter += char
else:
return ""
#encode a message in morse code, spaces between words are represented by '/'
def encodeToMorse(message):
encodedMessage = ""
for char in message[:]:
encodedMessage += morseAlphabet[char.upper()] + " "
return encodedMessage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment