Why is string sorted in alphabetic order?

Viewed 99

This is from Leetcode 804: Unique Morse Code Words. I am wondering why my code gives the right Morse code but it is sorted in alphabetic order which is not on purpose. Any contribution is appreciated.

Input:

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

code:

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        alphabet = ['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']
        transformation = []
        zip_ = list(zip(morse, alphabet))
        for word in words:
            transformation.append(''.join(code[0] for code in zip_ for letter in word if letter in code[1]))

output:

['--...-.', '.-.--..', '--.--...', '--.--...']    
2 Answers

The problem is that you first iterate through the zip_, and then through the letters. That's what is causing the alphabetical order -- zip_ is alphabetically sorted.

This version does what you want it to do:

 class Solution: 
      def uniqueMorseRepresentations(self, words: List[str]) -> int: 
          morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 
          alphabet = ['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'] 
          transformation = [] 
          zip_ = list(zip(morse, alphabet)) 
          for word in words: 
              transformation.append(''.join(code[0] for letter in word for code in zip_  if letter in code[1]))

It is not the most Pythonic way of doing it, but it is the smallest fix to your solution.

Personally, I would use a dictionary mapping letters to Morse code, and then iterate through the characters of the string. This is kind of similar to https://stackoverflow.com/users/6553328/emma 's solution, but a bit easier to read for people who don't know the integer values of chars.

Not sure about the problem that you're facing, this'll pass though:

class Solution:
    def uniqueMorseRepresentations(self, words):
        morse_map = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
             "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
        return len({''.join(morse_map[ord(char) - 97] for char in word) for word in words})

97 is ord('a'):

class Solution:
    def uniqueMorseRepresentations(self, words):
        morse_map = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
             "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
        return len({''.join(morse_map[ord(char) - ord('a')] for char in word) for word in words})

I don't see a return statement or a set() in your solution. There are two simple steps:

  • Add visited transformations into a set
  • Return the length of the set

Here is also a Java version using a HashSet (similar to the set() in Python), if you'd be interested:

public final class Solution {
    public static final int uniqueMorseRepresentations(
        final String[] words
    ) {
        final String[] morseMap = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
        Set<String> transformations = new HashSet<>();

        for (String word : words) {
            StringBuilder transformation = new StringBuilder();

            for (int index = 0; index < word.length(); index++)
                transformation.append(morseMap[word.charAt(index) - 97]);

            transformations.add(transformation.toString());
        }

        return transformations.size();
    }
}

References

  • For additional details, please see the Discussion Board where you can find plenty of well-explained accepted solutions with a variety of languages including low-complexity algorithms and asymptotic runtime/memory analysis1, 2.
Related