Created
February 16, 2012 05:55
-
-
Save ebuckley/1842461 to your computer and use it in GitHub Desktop.
python code to encode/decode morse code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Am I being an idiot or something, cause when I copy and paste this code to test it nothing happens, am I supposed to change something?
Same for me Glenderman
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
here is an example, with numbers, signs and a different function for decodeMorse
https://gist.github.com/dcdeve/3dfba6566029f87b01aa3e38d6e1e26b
My function for decodeMorse is