To get the common letters in two words without repetition

前端 未结 4 683
北海茫月
北海茫月 2021-01-29 10:29

Write the function getCommonLetters(word1, word2) that takes in two words as arguments and returns a new string that contains letters found in both string. Ignore r

相关标签:
4条回答
  • 2021-01-29 10:58

    If you want correction to your solution, then the problem is that you return the first common letter that you find. You have to continue searching for common letters and combine them into a result:

    def getCommonLetters(word1, word2):
       res = ""
    
       for letter in word1:
          if letter in word2:
             if letter not in res: # skip if we already found it
                 # don't return yet, but rather accumulate the letters
                 res = res + letter
    
       return res
    

    The solutions suggesting using set can be faster, especially if you are checking long words.

    0 讨论(0)
  • 2021-01-29 11:02
    >>> ''.join(sorted(set([letter for letter in word1 if letter in word2])))
    

    Explanation:

    1. [letter for letter in word1 if letter in word2]: Iterate over the letters in word1 and check if the current letter is contained by word2. If so add it to the list of common letters (with duplicates).
    2. set( 1. ): Remove duplicates by creating a set out of the list of common letters.
    3. sorted( 2. ): Sort the common letters (alphabetically).
    4. ''.join( 3. ): Create a string, joining the common letters by whitespaces (without duplicates).
    0 讨论(0)
  • 2021-01-29 11:03

    You can use set intersection

    >>> ''.join(set('apple').intersection(set('google')))
    'el'
    

    The function can be defined as

    def getCommonLetters(a, b):
        return ''.join(sorted(set(a).intersection(set(b))))
    

    Example

    >>> def getCommonLetters(a, b):
    ...         return ''.join(sorted(set(a).intersection(set(b))))
    ... 
    >>> getCommonLetters('google','apple')
    'el'
    
    0 讨论(0)
  • 2021-01-29 11:21

    you can use set() and set intersection to find the common elements of two sets -

    def getCommonLetters(word1, word2):
        return ''.join(sorted(set(word1) & set(word2)))
    

    & is for set intersection .


    Example/Demo -

    >>> def getCommonLetters(word1, word2):
    ...     return ''.join(sorted(set(word1) & set(word2)))
    ...
    >>> getCommonLetters('apple','google')
    'el'
    >>> getCommonLetters('microsoft','apple')
    ''
    
    0 讨论(0)
提交回复
热议问题