{"id":109469,"date":"2020-02-21T09:35:00","date_gmt":"2020-02-21T09:35:00","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=6326"},"modified":"2020-02-21T09:35:00","modified_gmt":"2020-02-21T09:35:00","slug":"a-simple-python-morse-code-translator","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/02\/21\/a-simple-python-morse-code-translator\/","title":{"rendered":"A Simple Python Morse Code Translator"},"content":{"rendered":"<p>Morse code was developed in telecommunications to encode the alphabetic characters in binary signals (&#8220;long&#8221; and &#8220;short&#8221;, or &#8220;1&#8221; and &#8220;0&#8221;). <\/p>\n<p>Here&#8217;s the Morse code table:<\/p>\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/02\/morsetable-1024x576.jpg\" alt=\"\" class=\"wp-image-6344\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/02\/morsetable-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/02\/morsetable-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/02\/morsetable-768x432.jpg 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><figcaption><em>Each character is mapped to its Morse code representation.<\/em><\/figcaption><\/figure>\n<p>This tutorial shows you how to implement a simple Morse code translator in Python.<\/p>\n<p>The code is contributed by<a href=\"https:\/\/blog.finxter.com\/subscribe\/\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\" Finxter student (opens in a new tab)\"> Finxter student<\/a> <strong>Albrecht<\/strong>. <\/p>\n<p><strong>Goal<\/strong>: Given a string that is either Morse code or normal text. Write a function that transforms the string into the other language: Morse code should be translated to normal text. Normal text should be translated to Morse code.<\/p>\n<p><strong>Output Example<\/strong>: Create a function <code>morse(txt)<\/code> that takes an input string argument <code>txt<\/code> and returns its translation:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> morse('python') '.--. -.-- - .... --- -.'\n>>> morse('.--. -.-- - .... --- -.') 'PYTHON'\n>>> morse(morse('HEY')) 'HEY'<\/pre>\n<p>Note that Morse code doesn&#8217;t differentiate lowercase or uppercase characters. So you just use uppercase characters as default translation output.<\/p>\n<p><strong>Algorithm<\/strong> <strong>Idea<\/strong>: A simple algorithm is enough to solve the problem:<\/p>\n<ul>\n<li>Detect if a string is Morse code or normal text. The simple but not perfect solution is to check if the first character is either the dot symbol <code>'.'<\/code> or the minus symbol <code>'-'<\/code>. Note that you can easily extend this by checking if all characters are either the dot symbol or the minus symbol (a simple <a rel=\"noreferrer noopener\" aria-label=\"regular expression (opens in a new tab)\" href=\"https:\/\/blog.finxter.com\/python-regex\/\" target=\"_blank\">regular expression<\/a> will be enough).<\/li>\n<li>Prepare a dictionary that maps all &#8220;normal text&#8221; symbols to their respective Morse code translations. Use the inverse dictionary (or create it ad-hoc) to get the inverse mapping.<\/li>\n<li>Iterate over all characters in the string and use the dictionary to translate each character separately.<\/li>\n<\/ul>\n<p><strong>Implementation<\/strong>: Here&#8217;s the Python implementation of the above algorithm for Morse code translation:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def morse(txt): '''Morse code encryption and decryption''' d = {'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':'--..', ' ':'.....'} translation = '' # Encrypt Morsecode if txt.startswith('.') or txt.startswith('\u2212'): # Swap key\/values in d: d_encrypt = dict([(v, k) for k, v in d.items()]) # Morse code is separated by empty space chars txt = txt.split(' ') for x in txt: translation += d_encrypt.get(x) # Decrypt to Morsecode: else: txt = txt.upper() for x in txt: translation += d.get(x) + ' ' return translation.strip() print(morse('python'))\n# .--. -.-- - .... --- -.\nprint(morse('.--. -.-- - .... --- -.'))\n# PYTHON\nprint(morse(morse('HEY')))\n# HEY\n<\/pre>\n<p><strong>Algorithmic complexity<\/strong>: The runtime complexity is linear in the length of the input string to be translated&#8212;one translation operation per character. <a rel=\"noreferrer noopener\" aria-label=\"Dictionary membership (opens in a new tab)\" href=\"https:\/\/blog.finxter.com\/python-dictionary\/\" target=\"_blank\">Dictionary membership<\/a> has constant runtime complexity. The memory overhead is also linear in the input text as all the characters have to be hold in memory.<\/p>\n<p><strong>Alternative<\/strong> <strong>Implementation<\/strong>: Albrecht also proposed a much shorter alternative:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def morse(txt): encrypt = {'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':'--..', ' ':'.....'} decrypt = {v: k for k, v in encrypt.items()} if '-' in txt: return ''.join(decrypt[i] for i in txt.split()) return ' '.join(encrypt[i] for i in txt.upper()) print(morse('python'))\n# .--. -.-- - .... --- -.\nprint(morse('.--. -.-- - .... --- -.'))\n# PYTHON\nprint(morse(morse('HEY')))\n# HEY\n<\/pre>\n<p>It uses dict comprehension and generator expressions to make it much more concise.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Morse code was developed in telecommunications to encode the alphabetic characters in binary signals (&#8220;long&#8221; and &#8220;short&#8221;, or &#8220;1&#8221; and &#8220;0&#8221;). Here&#8217;s the Morse code table: Each character is mapped to its Morse code representation. This tutorial shows you how to implement a simple Morse code translator in Python. The code is contributed by Finxter [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-109469","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/109469","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=109469"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/109469\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=109469"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=109469"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=109469"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}