Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
2 solutions solution in Clear category for Morse Decoder by donnythelegend
MORSE = {'.-': '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', '-----': '0',
'.----': '1', '..---': '2', '...--': '3',
'....-': '4', '.....': '5', '-....': '6',
'--...': '7', '---..': '8', '----.': '9'
}
def morse_decoder(code):
## Solution 1: The long way.
## Split code into words using triple whitespace.
#words = code.split(' ')
## Initialize empty object for letters.
#letters = None
## Initialize decode string.
#decode = ''
## Loop through words.
#for w in words:
# # Point letters to new list from split word.
# letters = w.split()
# # Loop through letters.
# for l in letters:
# # Add MORSE value with key l to decode.
# decode += MORSE[l]
# # Add a whitespace to decode after the full word has been translated.
# decode += ' '
# Return decode with removed final whitespace and first character capitalized.
#return decode[:-1].capitalize()
# Solution 2: One liner.
# This line splits code into words, splits the words into letters,
# joins the translated letters together, joins the translated words with whitespaces,
# then capitalizes the first character of the result.
return ' '.join(''.join(MORSE[letter] for letter in word.split()) for word in code.split(' ')).capitalize()
if __name__ == '__main__':
print("Example:")
print(morse_decoder('... --- ...'))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert morse_decoder("... --- -- . - . -..- -") == "Some text"
assert morse_decoder("..--- ----- .---- ---..") == "2018"
assert morse_decoder(".. - .-- .- ... .- --. --- --- -.. -.. .- -.--") == "It was a good day"
print("Coding complete? Click 'Check' to earn cool rewards!")
April 20, 2021
Comments: