Skip to content

Instantly share code, notes, and snippets.

@Saluev Saluev/morse.py

Last active Feb 27, 2018
Embed
What would you like to do?
Morse code with Python unary + and - operators
# -*- 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
You can’t perform that action at this time.