-
Notifications
You must be signed in to change notification settings - Fork 5
/
Morse code
76 lines (61 loc) · 1.54 KB
/
Morse code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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": "--..",
}
def encode_morse_code(text):
"""Encodes a text string into Morse code.
Args:
text: A string containing the text to be encoded.
Returns:
A string containing the encoded Morse code.
"""
morse_code = ""
for character in text:
morse_code += MORSE_CODE_DICT[character] + " "
return morse_code
def decode_morse_code(morse_code):
"""Decodes a Morse code string into a text string.
Args:
morse_code: A string containing the Morse code to be decoded.
Returns:
A string containing the decoded text.
"""
text = ""
for word in morse_code.split(" "):
for character, code in MORSE_CODE_DICT.items():
if code == word:
text += character
break
return text
# Example usage:
# Encode a text string into Morse code.
encoded_morse_code = encode_morse_code("Hello, world!")
# Decode the Morse code string back into a text string.
decoded_text = decode_morse_code(encoded_morse_code)
# Print the results.
print("Encoded Morse code:", encoded_morse_code)
print("Decoded text:", decoded_text)