Reputation: 51
I have a morse program but the spaces in between the words are not showing does any one have any ideas? Prefer the simplest way to do so
sample input:
APRIL FOOLS DAY
output for encode_Morse function:
' .- .--. .-. .. .-.. ..-. --- --- .-.. ... -.. .- -.-- '
output for the decode_Morse function:
APRILFOOLSDAY
MORSE_CODES={'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':' --.. '}
##Define functions here
def encode_Morse(my_msg):
#my_msg=my_msg.upper()
my_msg_Morse=""
for letter in my_msg:
if letter!=" " and letter not in MORSE_CODES:
my_msg_Morse+="*"
elif letter!=" ":
my_msg_Morse+= MORSE_CODES[letter]
else:
my_msg_Morse+=" "
return my_msg_Morse+""
def decode_Morse(my_msg):
string=""
for word in my_msg.split(" "):
for ch in word.split():
if ch!=" " and ch!="*":
string=string + list(MORSE_CODES.keys())[list(MORSE_CODES.values()).index(" "+ch+" ")]
elif ch==" ":
string+=" "
string=string+""
return string
Upvotes: 0
Views: 253
Reputation: 2518
I propse you this solution:
MORSE_CODES={
'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':'--..'
}
R_MORSE_CODES = {v:k for k,v in MORSE_CODES.items()}
def encode_morse(msg):
words = msg.split()
return " ".join(" ".join(MORSE_CODES.get(c, '*') for c in w) for w in words)
def decode_morse(msg):
words = msg.split(" ")
return " ".join("".join(R_MORSE_CODES.get(c, '?') for c in w.split()) for w in words)
# Original message
msg = "APRIL FOOLS DAY"
enc_msg = encode_morse(msg)
print(enc_msg)
# .- .--. .-. .. .-.. ..-. --- --- .-.. ... -.. .- -.--
dec_msg = decode_morse(enc_msg)
print(dec_msg)
# APRIL FOOLS DAY
Deviating from your solution, I
For back translation i reverse the dictionary keys and values to another translation table called R_MORSE_CODES
for better readability.
Using one and two spaces is sufficient to allow compatibility to decode a morse code back to its original message, as long as any unknown characters appear.
Upvotes: 0
Reputation: 1388
The split function absorbes your delimiter
I propose :
def decode_Morse(my_msg):
words = []
for word in my_msg.split(" "):
string = ""
for ch in word.split():
string=string + list(MORSE_CODES.keys())[list(MORSE_CODES.values()).index(" "+ch+" ")]
words.append(string)
return " ".join(words)
Upvotes: 1