Converting Words to Morse Code in Python and VBA

Python Implementation

The following Python function maps each letter of a word to its corresponding Morse code using a dictionary. It then stores the resulting Morse code strings in a set to ensure uniqueness and returns the count of these unique codes.


"""
# Define a dictionary mapping letters to Morse code
morse_code = {
    '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': "--.."
}

# Use a set to store unique Morse code representations
unique_morse = set()

# Process each word in the input list
for word in words:
    morse_word = ''
    # Convert each character in the word to Morse code
    for char in word:
        morse_word += morse_code[char.lower()]
    # Add the generated Morse code string to the set
    unique_morse.add(morse_word)

# Return the number of unique Morse code representations
return len(unique_morse)

Here's an example of how to use the function:


if __name__ == '__main__':
    input_words = ["myelsa", "my", "myelsa", "my"]
    solution = Solution()
    print("Input:", input_words)
    print("Output:", solution.uniqueMorseRepresentations(input_words))

Expectde Output:


Input: ['myelsa', 'my', 'myelsa', 'my']
Output: 2

VBA Implementatoin

The following VBA function performs a similar task by converting words into Morse code. It uses dictionaries to store the mappings and ensures that only unique Morse code strings are counted.


Rem Custom function to convert words to Morse code
Function UniqueMorseRepresentations(words() As Variant) As Long
    ' Declare objects for Morse code dictionary and unique codes
    Dim morseDict As Object, uniqueMorse As Object
    ' Declare loop counters and variables
    Dim i As Integer, j As Integer
    Dim word As Variant
    Dim morseWord As String, char As String

    ' Define Morse code and letters as constants
    Const morseCode As String = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ..- ...- .-- -..- -.-- --.."
    Const letters As String = "abcdefghijklmnopqrstuvwxyz"

    ' Create and populate the Morse code dictionary
    Set morseDict = CreateObject("Scripting.Dictionary")
    For i = 1 To Len(letters)
        morseDict.Add Mid(letters, i, 1), Mid(morseCode, i * 3 - 2, 3)
    Next i

    ' Create a dictionary to store unique Morse code strings
    Set uniqueMorse = CreateObject("Scripting.Dictionary")

    ' Process each word in the input array
    For Each word In words
        morseWord = ""
        ' Convert each character in the word to Morse code
        For j = 1 To Len(word)
            char = LCase(Mid(word, j, 1))
            If morseDict.Exists(char) Then
                morseWord = morseWord & morseDict(char)
            End If
        Next j
        ' Add the Morse code string if it's not already present
        If Not uniqueMorse.Exists(morseWord) Then
            uniqueMorse.Add morseWord, Nothing
        End If
    Next word

    ' Return the count of unique Morse code strings
    UniqueMorseRepresentations = uniqueMorse.Count
End Function

Rem Test procedure to call the function
Sub TestRun()
    Dim input_words() As Variant
    Dim result As Long

    ' Initialize input array
    input_words = Array("myelsa", "my", "myelsa", "my")
    ' Call the function and print the result
    result = UniqueMorseRepresentations(input_words)
    Debug.Print "Output: " & result
End Sub

To run the VBA code, paste it into your VBA editor and press F5 to execute the TestRun subroutine. The result will be displayed in the Immediate window.

Tags: Morse code python VBA Dictionary algorithm

Posted on Wed, 26 Aug 2026 16:08:02 +0000 by dasmon777