Hi,
This question was asked by an interviewer to me, for the company Bombay Softwares. I have written the solution code in Python, below. The problem becomes easy if we use ‘ord’, the Python’s inbuilt function to find the Unicode number of the given character. For example ‘a’ has a Unicode number of 97, hence if I write, ord(‘a’), the output will be an integer 97.
Question : (reference : leetecode.com)
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.
For convenience, the full table for the 26
letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Given an array of strings where each word can be written as a concatenation of the Morse code of each letter.
- For example,
"cab"
can be written as"-.-..--..."
, which is the concatenation of"-.-."
,".-"
, and"-..."
. We will call such a concatenation the transformation of a word.
Return the number of different transformations among all words we have.
Example 1:
Input: words = ["gin","zen","gig","msg"] Output: 2
Solution Code:
Morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
# letters_list = ['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']
def listmorse(A):
Morse_list_codes = []
for word in A:
word = str(word)
list_letters = list(word)
morse_word = ''
for letter in list_letters:
n = ord(letter)
no = ord('a')
index = n - no
morse_code_ltr = Morse[index]
morse_word = morse_word + morse_code_ltr
Morse_list_codes.append(morse_word)
return Morse_list_codes
Morse_codes = listmorse(["gin","zen","gig","msg"])
print(Morse_codes)
list_set = set(Morse_codes)
print(len(list_set))