Advertisement
Guest User

brutemorse.py

a guest
Jun 21st, 2021
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. #!/usr/bin/python3
  2. #brutemorse.py
  3. morse2abc={".-":"a", "-...":"b", "-.-.":"c", "-..":"d", ".":"e", "..-.":"f", "--.":"g", "....":"h", "..":"i", ".---":"j", "-.-":"k", ".-..":"l", "--":"m", "-.":"n", "---":"o", ".--.":"p", "--.-":"q", ".-.":"r", "...":"s", "-":"t", "..-":"u", "...-":"v", ".--":"x", "-..-":"y", "-.--":"z"}
  4. abc2morse = dict((v,k) for k,v in morse2abc.items())
  5.  
  6. def print_to_morse(string):
  7. return "/".join(abc2morse[c] for c in string)
  8.  
  9. # morse_string = original input string of dots and dashes
  10. # maxlength = optional arg to limit length of decoded text
  11. def unmorse(morse_string, maxlength=0):
  12. unmorse_recursive(morse_string, 0, "", maxlength)
  13.  
  14. def unmorse_recursive(morse_string, startindex, prev_text, maxlength=0):
  15. # try to decode next 1-4 dots and dashes into a character
  16. for i in range(startindex+1,startindex+5):
  17. substring_next = morse_string[startindex:i]
  18. if substring_next in morse2abc:
  19. next_char = morse2abc[substring_next]
  20. # if reached end of input string, print result
  21. if i == len(morse_string):
  22. text = prev_text + next_char
  23. if (maxlength == 0) or (len(text) == maxlength):
  24. print("{0} ({1})".format(text, print_to_morse(text)))
  25. # otherwise recurse
  26. else:
  27. unmorse_recursive(morse_string, i, prev_text + next_char, maxlength)
  28.  
  29. unmorse("-............",6)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement