Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] A Simple Python Morse Code Translator

#1
A Simple Python Morse Code Translator

<div><p>Morse code was developed in telecommunications to encode the alphabetic characters in binary signals (“long” and “short”, or “1” and “0”). </p>
<p>Here’s the Morse code table:</p>
<figure class="wp-block-image size-large"><img 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/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption><em>Each character is mapped to its Morse code representation.</em></figcaption></figure>
<p>This tutorial shows you how to implement a simple Morse code translator in Python.</p>
<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>
<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>
<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>
<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') '.--. -.-- - .... --- -.'
>>> morse('.--. -.-- - .... --- -.') 'PYTHON'
>>> morse(morse('HEY')) 'HEY'</pre>
<p>Note that Morse code doesn’t differentiate lowercase or uppercase characters. So you just use uppercase characters as default translation output.</p>
<p><strong>Algorithm</strong> <strong>Idea</strong>: A simple algorithm is enough to solve the problem:</p>
<ul>
<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>
<li>Prepare a dictionary that maps all “normal text” symbols to their respective Morse code translations. Use the inverse dictionary (or create it ad-hoc) to get the inverse mapping.</li>
<li>Iterate over all characters in the string and use the dictionary to translate each character separately.</li>
</ul>
<p><strong>Implementation</strong>: Here’s the Python implementation of the above algorithm for Morse code translation:</p>
<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('−'): # 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'))
# .--. -.-- - .... --- -.
print(morse('.--. -.-- - .... --- -.'))
# PYTHON
print(morse(morse('HEY')))
# HEY
</pre>
<p><strong>Algorithmic complexity</strong>: The runtime complexity is linear in the length of the input string to be translated—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>
<p><strong>Alternative</strong> <strong>Implementation</strong>: Albrecht also proposed a much shorter alternative:</p>
<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'))
# .--. -.-- - .... --- -.
print(morse('.--. -.-- - .... --- -.'))
# PYTHON
print(morse(morse('HEY')))
# HEY
</pre>
<p>It uses dict comprehension and generator expressions to make it much more concise.</p>
</div>


https://www.sickgaming.net/blog/2020/02/...ranslator/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016