Konverter Kode Morse
Ubah teks menjadi kode Morse dan dekode kode Morse kembali menjadi teks.
Referensi
0
−−−−−
1
·−−−−
2
··−−−
3
···−−
4
····−
5
·····
6
−····
7
−−···
8
−−−··
9
−−−−·
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
−−··
Pertanyaan yang Sering Diajukan
Implementasi Kode
# Morse Code Encoder / Decoder
MORSE_CODE = {
'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': '----.',
'.': '.-.-.-', ',': '--..--', '?': '..--..', '/': '-..-.',
}
REVERSE_MORSE = {v: k for k, v in MORSE_CODE.items()}
def encode(text: str) -> str:
"""Convert plain text to Morse code."""
result = []
for word in text.upper().split():
coded_word = ' '.join(MORSE_CODE.get(ch, '?') for ch in word)
result.append(coded_word)
return ' / '.join(result) # '/' separates words
def decode(morse: str) -> str:
"""Convert Morse code back to plain text."""
words = morse.strip().split(' / ')
result = []
for word in words:
letters = [REVERSE_MORSE.get(sym, '?') for sym in word.split()]
result.append(''.join(letters))
return ' '.join(result)
# Examples
print(encode("SOS")) # ... --- ...
print(encode("HELLO WORLD")) # .... . .-.. .-.. --- / .-- --- .-. .-.. -..
print(decode("... --- ...")) # SOS
print(decode(".... . .-.. .-.. --- / .-- --- .-. .-.. -..")) # HELLO WORLDComments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.