By Ben Cholye
I’m building a Morse code encoder/decoder in Python and ran into an issue when decoding messages that contain multiple spaces or unsupported symbols.
The decoder works fine for simple inputs like:
… . .-… .-… —
which correctly outputs: HELLO
But when the input contains word separators or unexpected characters, the output becomes inconsistent.
Example problematic input: … . .-… .-… — .-- — .-. .-… -… @
Expected output: HELLO WORLD
Actual behavior:
@ break the parserKeyError exceptionsCurrent decoding logic:
MORSE_CODE_DICT = { ‘.-’: ‘A’, ‘-…’: ‘B’, # … }
decoded = “”
for code in morse_input.split(" "): decoded += MORSE_CODE_DICT[code]
Questions:
What’s the best way to safely handle invalid Morse sequences? How should multiple spaces be interpreted when separating words? Is there a more robust parsing strategy for Morse code decoding in Python?
Any suggestions or best practices would be appreciated.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.