Skip to content

Instantly share code, notes, and snippets.

@downbtn
Last active July 7, 2021 21:25
Show Gist options
  • Save downbtn/66d71c30b03b4174a15a2a2570dfca37 to your computer and use it in GitHub Desktop.
Save downbtn/66d71c30b03b4174a15a2a2570dfca37 to your computer and use it in GitHub Desktop.
the
#!/usr/bin/env python
MORSE_CODE_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': '--..',
'1': '.----',
'2': '..---',
'3': '...--',
'4': '....-',
'5': '.....',
'6': '-....',
'7': '--...',
'8': '---..',
'9': '----.',
'0': '-----',
',': '--..--',
'.': '.-.-.-',
'?': '..--..',
'/': '-..-.',
'-': '-....-',
'(': '-.--.',
')': '-.--.-',
}
REVERSE_MORSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()}
def verify(text: str) -> bool:
for char in text:
if char not in MORSE_CODE_DICT and char != ' ':
print('unsupported character!!')
return False
return True
def bubble_morse(text: str) -> str:
text = text.upper()
new_text = ''
if not verify(text):
return 'no'
for letter in text:
if letter == ' ':
continue
new_text += MORSE_CODE_DICT[letter]
new_text += '/ '
return new_text.replace('.', ':heart: ').replace('-', ':bubble_tea: ')[:-3]
def unbubble_morse(bubbled_text: str) -> str:
# remove spaces
bubbled_text = ''.join(bubbled_text.split())
bubbled_letters = bubbled_text.split('/')
unbubbled = ''
for letter in bubbled_letters:
if letter:
unbubbled_letter = letter.replace(':heart:', '.').replace(
':bubble_tea:', '-')
unbubbled += REVERSE_MORSE_DICT[unbubbled_letter]
return unbubbled
if __name__ == '__main__':
print(bubble_morse(input('encrypt: ')))
print(unbubble_morse(input('decrypt: ')))
@BitLegion
Copy link

GODLY

@downbtn
Copy link
Author

downbtn commented Sep 29, 2020

Updated to fix a bug. Spaces are no longer supported.

@BitLegion
Copy link

Just use .split()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment