aboutsummaryrefslogtreecommitdiff
path: root/challenge-035/lubos-kolouch/python/ch-1.py
blob: a9d929615a1c1acadfcecc5ad4a90e7369f48f91 (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest

# Define Morse code mappings
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": "--..",
    " ": "/",
}


# Encode text into binary encoded Morse code
def encode_morse(text):
    encoded = ""
    for char in text.upper():
        if char in morse_code:
            morse = morse_code[char]
            bits = []
            for symbol in morse:
                if symbol == ".":
                    bits.extend(["1", "0"])
                elif symbol == "-":
                    bits.extend(["1" * 3, "0"])
            encoded += "0".join(bits) + "0"
    encoded = encoded.rstrip("0")  # Remove trailing intra-character gap
    return encoded


# Define tests
class TestMorseEncoding(unittest.TestCase):
    def test_hello_world(self):
        encoded_text = encode_morse("HELLO WORLD")
        self.assertEqual(
            encoded_text,
            "1010100011101110111010111000101110100010111010001110101000101011100010111010001110100011101011100010101110001011101000101110100010111010001110100011101011100010111010001110100011101011100010101110001011101",
        )