Editor

Morse Code

#240 · Codes and ciphers · Beginner · 35 XP · about 8 min

Morse code spells every letter and digit as a short pattern of dots (.) and dashes (-), so a message can be sent with a single key or a flashing light. Write to_morse(text) that returns the Morse code for text as one string:

  • inside a word, the codes of its characters are separated by one space;
  • words are separated by a slash with one space on each side, ' / ';
  • a lower case letter has the same code as its capital.

text contains only letters, digits and spaces, with exactly one space between words and none at the start or end. The empty string gives the empty string.

Here is the whole table (your starter code already has it as the dictionary MORSE, with capital letters as keys):

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 ----.

Examples

to_morse("SOS")       # returns '... --- ...'
to_morse("Hi Bob")    # returns '.... .. / -... --- -...'
to_morse("Room 101")  # returns '.-. --- --- -- / .---- ----- .----'

In the second example, H is .... and i is .., so the first word is .... ..; then comes the word separator ' / ' and the three codes of Bob.

Constraints

  • text has 0 to 1,000 characters.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.