-
Notifications
You must be signed in to change notification settings - Fork 0
/
morse_code_pt2.py
67 lines (49 loc) · 2.88 KB
/
morse_code_pt2.py
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
'''
In this kata you have to write a Morse code decoder for wired electrical telegraph.
Electric telegraph is operated on a 2-wire line with a key that, when pressed, connects the wires together, which can be detected on a remote station. The Morse code encodes every character being transmitted as a sequence of "dots" (short presses on the key) and "dashes" (long presses on the key).
When transmitting the Morse code, the international standard specifies that:
"Dot" – is 1 time unit long.
"Dash" – is 3 time units long.
Pause between dots and dashes in a character – is 1 time unit long.
Pause between characters inside a word – is 3 time units long.
Pause between words – is 7 time units long.
However, the standard does not specify how long that "time unit" is. And in fact different operators would transmit at different speed. An amateur person may need a few seconds to transmit a single character, a skilled professional can transmit 60 words per minute, and robotic transmitters may go way faster.
For this kata we assume the message receiving is performed automatically by the hardware that checks the line periodically, and if the line is connected (the key at the remote station is down), 1 is recorded, and if the line is not connected (remote key is up), 0 is recorded. After the message is fully received, it gets to you for decoding as a string containing only symbols 0 and 1.
For example, the message HEY JUDE, that is ···· · −·−− ·−−− ··− −·· · may be received as follows:
1100110011001100000011000000111111001100111111001111110000000000000011001111110011111100111111000000110011001111110000001111110011001100000011
As you may see, this transmission is perfectly accurate according to the standard, and the hardware sampled the line exactly two times per "dot".
'''
def DecodeBits(bits):
bits = bits.strip('0')
bits_dictionary = {}
last_bit = 0
aux = 0
for i in bits:
if i == '0':
if last_bit == '0':
bits_dictionary[aux] = bits_dictionary[aux] + 1
else:
aux = aux + 1
bits_dictionary[aux] = 1
if i == '1':
if last_bit == '1':
bits_dictionary[aux] = bits_dictionary[aux] + 1
else:
aux = aux + 1
bits_dictionary[aux] = 1
last_bit = i
min_repeated_times = min( list( bits_dictionary.values() ) )
print(bits_dictionary)
morse = []
for key, value in bits_dictionary.items():
if key%2 != 0:
if value == min_repeated_times:
morse.append('.')
else:
morse.append('-')
elif key%2 == 0:
if value == 7*min_repeated_times:
morse.append(' ')
if value == 3*min_repeated_times:
morse.append(' ')
return(''.join(morse))