Created
October 2, 2018 01:47
-
-
Save yammesicka/773a9fa6b5bef68eabd285439d7cb287 to your computer and use it in GitHub Desktop.
Morse code bruteforce
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
MORSE_TRANSLATION = { | |
".-": "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", | |
} | |
MAX_MORSE_CODE_SIZE = len(max(MORSE_TRANSLATION.keys(), key=len)) | |
def _all_options(n, options, road): | |
for option in options: | |
if n - option == 0: | |
yield road + [option] | |
return [] | |
elif n - option < 0: | |
return [] | |
yield from _all_options(n - option, options, road + [option]) | |
def all_options(n, options, road=None): | |
if road is None: | |
road = [] | |
yield from _all_options(n, sorted(options), road) | |
def translate_from_morse(morse, option): | |
sentence = '' | |
for letter_pos in option: | |
letter, morse = morse[:letter_pos], morse[letter_pos:] | |
sentence += MORSE_TRANSLATION[letter] | |
return sentence | |
def morse_bruteforce(morse): | |
for option in all_options(len(morse), range(1, MAX_MORSE_CODE_SIZE + 1)): | |
yield translate_from_morse(morse, option) | |
if __name__ == '__main__': | |
assert len(list(all_options(10, range(1, 3)))) == 89 | |
assert translate_from_morse('.....', [1] * 5) == 'EEEEE' | |
assert translate_from_morse('.....', [3, 2]) == 'SI' | |
assert 'YAY' in morse_bruteforce("-.--.--.--") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment