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

import re
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",
    "/": " ",
}


# Decode binary encoded Morse code
def decode_morse(encoded):
    # Split encoded text into words and characters
    words = re.findall("0{7}", encoded + "0000000")
    letters = [re.findall("0{3}", word + "000") for word in words]
    # Convert Morse code to plaintext
    plaintext = ""
    for word in letters:
        for letter in word:
            if letter in morse_code:
                plaintext += morse_code[letter]
            else:
                # If the Morse code is badly formed, try to recover by looking one digit ahead
                for i in range(1, 4):
                    lookahead = letter[i:]
                    if lookahead in morse_code:
                        plaintext += morse_code[lookahead]
                        break
                else:
                    # If no valid Morse code sequence can be recovered, treat the character as a space
                    plaintext += " "
    return plaintext