Unique Morse Code Words in Python



Suppose we have a list of words, here each word can be written as a concatenation of the Morse code of each letter. For example, the word "cba" can be written as "-.-..--...", this is the concatenation "-.-." | "-..." | ".-"). This kind of concatenation is called the transformation of a word.

We know that International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.

Here is the list of all 26 letters of the English alphabet is as follows −

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","- ","..-","...-",".--","-..-","-.--","--.."]

So, if the input is like ["gin", "zen", "gig", "msg"], then the output will be 2, as The transformation of each word is: "gin" will be "--...-.", "zen" will be "--...-." "gig" will be "--...--." and "msg" will be "--...--.".

To solve this, we will follow these steps −

  • morse_codes:= [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
  • s:= a new set
  • for each word in words, do
    • temp:= blank string
    • for each c in word, do
      • temp := temp + morse_codes[ASCII of c - 97]
    • add temp into s
  • return size of s

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def uniqueMorseRepresentations(self, words):
      morse_codes=[".-","-...","-.-.","-..",".","..-.","--
      .","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-
      .","...","-","..-","...-",".--","-..-","-.--","--.."]
      s=set()
      for word in words:
         temp=''
         for c in word:
            temp+=morse_codes[ord(c)-97]
         s.add(temp)
      return len(s)
ob = Solution()
print(ob.uniqueMorseRepresentations(["gin", "zen", "gig", "msg"]))

Input

["gin", "zen", "gig", "msg"]

Output

2

Advertisements