Created
June 15, 2020 08:05
-
-
Save kremerben/93f3083381aa80f2e017f50705037662 to your computer and use it in GitHub Desktop.
Encoding and decoding morse code strings
This file contains 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
morsecode_map = dict(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="--..") | |
def reverse_python_dict(dict_: dict) -> dict: | |
return {dict_[k]:k for k in dict_} | |
def encode_morsecode(str_: str) -> str: | |
result = "" | |
for letter in str_: | |
if letter == " ": | |
result += " " | |
else: | |
result += " " + morsecode_map[letter] | |
return result[1:] | |
def decode_morsecode(str_: str) -> str: | |
""" Expects one space between letters, and 2 spaces between words.""" | |
decode_map = reverse_python_dict(morsecode_map) | |
result = "" | |
for word in str_.split(" "): | |
result += " " | |
for letter in word.split(" "): | |
result += decode_map[letter] | |
return result[1:] | |
reverse_python_dict(morsecode_map) | |
encode_morsecode('hello worlds') | |
decode_morsecode(encode_morsecode('hello worlds')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment