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

Morse code was developed in telecommunications to encode the alphabetic characters in binary signals (“long” and “short”, or “1” and “0”).

Here’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 student Albrecht.

Goal: 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.

Output Example: Create a function morse(txt) that takes an input string argument txt and returns its translation:

>>> morse('python') '.--. -.-- - .... --- -.'
>>> morse('.--. -.-- - .... --- -.') 'PYTHON'
>>> morse(morse('HEY')) 'HEY'

Note that Morse code doesn’t differentiate lowercase or uppercase characters. So you just use uppercase characters as default translation output.

Algorithm Idea: A simple algorithm is enough to solve the problem:

  • 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 '.' or the minus symbol '-'. Note that you can easily extend this by checking if all characters are either the dot symbol or the minus symbol (a simple regular expression will be enough).
  • 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.
  • Iterate over all characters in the string and use the dictionary to translate each character separately.

Implementation: Here’s the Python implementation of the above algorithm for Morse code translation:

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

Algorithmic complexity: The runtime complexity is linear in the length of the input string to be translated—one translation operation per character. Dictionary membership has constant runtime complexity. The memory overhead is also linear in the input text as all the characters have to be hold in memory.

Alternative Implementation: Albrecht also proposed a much shorter alternative:

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

It uses dict comprehension and generator expressions to make it much more concise.



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



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Tuple Concatenation: A Simple Illustrated Guide xSicKxBot 0 1,942 08-21-2023, 10:25 AM
Last Post: xSicKxBot
  [Tut] Python Async With Statement — Simplifying Asynchronous Code xSicKxBot 0 1,339 04-28-2023, 03:04 AM
Last Post: xSicKxBot
  [Tut] OpenAI API – or How I Made My Python Code Intelligent xSicKxBot 0 1,280 01-25-2023, 06:53 AM
Last Post: xSicKxBot
  [Tut] 10 Simple Ideas – Coding Projects to Create Real Value xSicKxBot 0 1,250 01-02-2023, 12:57 PM
Last Post: xSicKxBot
  [Tut] Python Library Hijacking – A Simple Demonstration on NumPy xSicKxBot 0 1,251 11-22-2022, 01:48 AM
Last Post: xSicKxBot
  [Tut] Parsing XML Files in Python – 4 Simple Ways xSicKxBot 0 1,180 11-13-2022, 10:49 AM
Last Post: xSicKxBot
  [Tut] Aave for DeFi Developers – A Simple Guide with Video xSicKxBot 0 1,434 10-01-2022, 09:43 AM
Last Post: xSicKxBot
  [Tut] Solidity by Example – Simple Open Auction (Explained) xSicKxBot 0 1,184 09-08-2022, 04:59 PM
Last Post: xSicKxBot
  [Tut] A Simple Guide for Using Command Line Arguments in Python xSicKxBot 0 1,134 08-14-2022, 05:49 PM
Last Post: xSicKxBot
  [Tut] 3 Simple Steps to Convert calendar.ics to CSV/Excel in Python xSicKxBot 0 1,283 08-12-2022, 01:58 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016