Last active
August 6, 2024 01:25
-
-
Save Saluev/c07bef8ffa7290345b0c816fed2ca418 to your computer and use it in GitHub Desktop.
Morse code with Python unary + and - operators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
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__": | |
from morse import * | |
_, ___ = Morse(), MorseWithSpace() | |
print(+--+_+-+_++_+--_+_-_+-+-+-___--+_++_-_++++_+-_-+++_--++--_) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment