Created
September 28, 2023 20:02
-
-
Save itolosa/e5f2b8ad2255a99c8e5e88320dcdb951 to your computer and use it in GitHub Desktop.
morse translator
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
import random | |
alphabet = { | |
".-": "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", | |
"-----": "0", | |
".----": "1", | |
"..---": "2", | |
"...--": "3", | |
"....-": "4", | |
".....": "5", | |
"-....": "6", | |
"--...": "7", | |
"---..": "8", | |
"----.": "9", | |
"/": " ", | |
} | |
def to_morse(text: str) -> str: | |
r = {value: key for key, value in alphabet.items()} | |
return " ".join(map(lambda c: r[c] if c in r else c, text)) | |
def to_text(morse: str) -> str: | |
return "".join(map(lambda c: alphabet[c] if c in alphabet else c, morse.split())) | |
def test() -> None: | |
assert to_text("... --- ...") == "SOS" | |
assert to_morse("SOS") == "... --- ..." | |
def random_sentence(n: int = 10) -> str: | |
alphabet_and_numbers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 " | |
return "".join([random.choice(alphabet_and_numbers) for _ in range(n)]) | |
for _ in range(100): | |
sentence = random_sentence() | |
assert to_text(to_morse(sentence)) == sentence | |
print("All tests passed!") | |
if __name__ == "__main__": | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment