惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

阮一峰的网络日志
阮一峰的网络日志
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
雷峰网
雷峰网
U
Unit 42
Y
Y Combinator Blog
I
InfoQ
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
量子位
Microsoft Security Blog
Microsoft Security Blog
B
Blog
The Cloudflare Blog
F
Fortinet All Blogs
Google DeepMind News
Google DeepMind News
MyScale Blog
MyScale Blog
C
Check Point Blog
S
SegmentFault 最新的问题
爱范儿
爱范儿
博客园 - 叶小钗
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Hugging Face - Blog
Hugging Face - Blog
罗磊的独立博客
T
Tailwind CSS Blog

DigitalOcean Community Questions

Referral Link Not Working anymore | DigitalOcean Recent console change has destroyed capacity to connect to legacy FreeBSD installs | DigitalOcean issue after moving app from aws to digitalocean | DigitalOcean issue after moving app from aws to digitalocean | DigitalOcean Container registry auomated garbage cillection sign in | DigitalOcean Billings And Free Tier Offer | DigitalOcean Switch hostinger to digitalocean? | DigitalOcean Unable to connect to Droplet via Console – “Failed to get droplet info” error | DigitalOcean billing problem | DigitalOcean How do I migrate an old Xen DomU VM, backed by a DRBD volume, to Digital Ocean? | DigitalOcean How to fix website not loading issue on VPS server (Nginx + WordPress) | DigitalOcean Account Locked After Payment Method Attempt (Hatch Program) - No Clear Reason | DigitalOcean Ghost Blog Marketplace Droplet is Ubuntu 22.04, not Ubuntu 24.04 | DigitalOcean How to setup browser with openclaw | DigitalOcean unable to load CA private key | DigitalOcean unable to load CA private key.. | DigitalOcean Add additional billing contact | DigitalOcean Digital Ocean Cloud Firewall? | DigitalOcean Mongodb auditing and compliance | DigitalOcean How much you're spending on AI tools? | DigitalOcean I can't create a managed MySQL cluster | DigitalOcean Please unblock SMTP (ports 25/465/587) for my droplet | DigitalOcean Reported promotional profile still accessible on DigitalOcean | DigitalOcean Change DNS server on Ubuntu 24 | DigitalOcean cannot add promotion of github student pack | DigitalOcean Do I need to use a Load Balancer on DigitalOcean for HTTPS or can I handle it on the Droplet? | DigitalOcean Best way to deploy a small Docker app on DigitalOcean without overengineering? | DigitalOcean Why is my DigitalOcean Droplet bandwidth usage so high all of a sudden? | DigitalOcean smtpout.secureserver.net 587 is blocked | DigitalOcean How do I disable AI? | DigitalOcean
Morse Code Decoder Fails on Consecutive Spaces and Specia...
By Ben Cholye · 2026-05-13 · via DigitalOcean Community Questions

Heya,

Your issues stem from three things: (1) dict[key] raises KeyError on unknown codes, (2) split(" ") produces empty strings when there are consecutive spaces, and (3) you’re not distinguishing letter separators (single space) from word separators (typically / or multiple spaces).

## The fix

### 1. Use dict.get() instead of dict[...]

dict.get(key, default) returns the default instead of raising KeyError. This alone solves the crash on @.

### 2. Standardize the word separator

The conventional Morse convention is:

  • 1 space between letters
  • 3 spaces (or a /) between words

Normalize the input first so the parser only deals with one format.

### 3. Parse in two levels: words → letters

Split on the word separator first, then on the letter separator. This makes empty tokens disappear naturally and makes the intent explicit.


## Working example

MORSE_CODE_DICT = {
    '.-':   '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 decode_morse(morse: str, unknown: str = '?') -> str:
    # Normalize: treat "/" as a word separator, collapse runs of spaces
    # into the canonical 3-space word break.
    normalized = morse.replace('/', '   ').strip()

    words = [w for w in normalized.split('   ') if w]
    decoded_words = []

    for word in words:
        letters = [MORSE_CODE_DICT.get(code, unknown)
                   for code in word.split(' ') if code]
        decoded_words.append(''.join(letters))

    return ' '.join(decoded_words)

### Test

>>> decode_morse('.... . .-.. .-.. ---   .-- --- .-. .-.. -..')
'HELLO WORLD'

>>> decode_morse('.... . .-.. .-.. ---   .-- --- .-. .-.. -.. @')
'HELLO WORLD?'

>>> decode_morse('.... . .-.. .-.. --- / .-- --- .-. .-.. -..')
'HELLO WORLD'

## Why this works

Problem Cause Fix
KeyError on @ dict[key] raises on miss dict.get(code, '?')
Empty decoded chars "a b".split(" ") yields ['a', '', 'b'] if code filter inside the comprehension
Words run together No distinction between letter/word gaps Split on " " first, then " "
Mixed separators Some sources use /, some use Normalize /" " up front

## A couple of further notes

  • Strict mode: if you’d rather reject invalid input than substitute ?, raise your own ValueError with the offending token — it’s friendlier than a bare KeyError:
    if code not in MORSE_CODE_DICT:
        raise ValueError(f"Invalid Morse token: {code!r}")
    
  • Encoder symmetry: when building the encoder, emit ' ' between letters and ' ' (three spaces) between words so a round-trip decode(encode(x)) == x.upper() holds for supported characters.
  • Regex alternative: re.split(r' {3,}', morse.strip()) for words and re.split(r' +', word) for letters also collapses runs gracefully if you prefer not to normalize first.

This pattern — normalize input → split coarse → split fine → lookup with default — generalizes well to any token-stream decoder, not just Morse.