I created this morse code encoder and decoder.
class DecodeError(BaseException):
__module__ = Exception.__module__
class EncodeError(BaseException):
__module__ = Exception.__module__
code_letter = {
'.-': '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',
'.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5',
'-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0',
'--..--': ', ', '.-.-.-': '.', '..--..': '?', '-..-.': '/',
'-....-': '-', '-.--.': '(', '-.--.-': ')', '/': ' '
}
letter_code = {value: key for key, value in zip(code_letter.keys(), code_letter.values())}
def morse_encode(string: str) -> str:
try:
return ' '.join(letter_code[i.upper()] for i in string)
except:
raise EncodeError('Unknown value in string')
def morse_decode(string: str) -> str:
try:
return ''.join(code_letter[i] for i in string.split())
except:
raise DecodeError('Unknown value in string')
if __name__ == '__main__':
string = input()
print(morse_encode(string))
Is it possible to make the code shorter while maintaining neatness?
Thanks!