-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathMorse code with Python unary + and - operators.py
126 lines (101 loc) · 2.63 KB
/
Morse code with Python unary + and - operators.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Morse code with Python unary + and - operators"""
# SOURCE: https://habrahabr.ru/post/349776/
# SOURCE: https://gist.github.com/Saluev/c07bef8ffa7290345b0c816fed2ca418
MORSE_ALPHABET = {
"А": ".-",
"Б": "-...",
"В": ".--",
"Г": "--.",
"Д": "-..",
"Е": ".",
"Ж": "...-",
"З": "--..",
"И": "..",
"Й": ".---",
"К": "-.-",
"Л": ".-..",
"М": "--",
"Н": "-.",
"О": "---",
"П": ".--.",
"Р": ".-.",
"С": "...",
"Т": "-",
"У": "..-",
"Ф": "..-.",
"Х": "....",
"Ц": "-.-.",
"Ч": "---.",
"Ш": "----",
"Щ": "--.-",
"Ъ": "--.--",
"Ы": "-.--",
"Ь": "-..-",
"Э": "..-..",
"Ю": "..--",
"Я": ".-.-",
"1": ".----",
"2": "..---",
"3": "...--",
"4": "....-",
"5": ".....",
"6": "-....",
"7": "--...",
"8": "---..",
"9": "----.",
"0": "-----",
".": "......",
",": ".-.-.-",
":": "---...",
";": "-.-.-.",
"(": "-.--.-",
")": "-.--.-",
"'": ".----.",
'"': ".-..-.",
"-": "-....-",
"/": "-..-.",
"?": "..--..",
"!": "--..--",
"@": ".--.-.",
"=": "-...-",
" ": " ",
}
INVERSE_MORSE_ALPHABET = {v: k for k, v in MORSE_ALPHABET.items()}
class Morse(object):
def __init__(self, buffer=""):
self.buffer = buffer
def __neg__(self):
return Morse("-" + self.buffer)
def __pos__(self):
return Morse("." + self.buffer)
def __str__(self):
return INVERSE_MORSE_ALPHABET[self.buffer]
def __repr__(self):
return str(self)
def __add__(self, other):
return str(self) + str(+other)
def __radd__(self, s):
return s + str(+self)
def __sub__(self, other):
return str(self) + str(-other)
def __rsub__(self, s):
return s + str(-self)
class MorseWithSpace(Morse):
def __str__(self):
return super().__str__() + " "
def __neg__(self):
return MorseWithSpace(super().__neg__().buffer)
def __pos__(self):
return MorseWithSpace(super().__pos__().buffer)
def morsify(s):
s = "_".join(map(MORSE_ALPHABET.get, s.upper()))
s = s.replace(".", "+") + ("_" if s else "")
s = s.replace("_ ", "__").replace(" _", "__")
return s
if __name__ == "__main__":
_, ___ = Morse(), MorseWithSpace()
print(+--+_ + -+_ + +_ + --_ + _ - _ + -+-+-___ - -+_ + +_ - _ + +++_ + -_ - +++_ - -++--_)
print(morsify("ПРИВЕТ ХАБР!")) # +--+_+-+_++_+--_+_-___++++_+-_-+++_+-+_--++--_
print(+--+_ + -+_ + +_ + --_ + _ - ___ + +++_ + -_ - +++_ + -+_ - -++--_)