To Get The Common Letters In Two Words Without Repetition
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 repeated letters
Solution 1:
you can use set()
and set intersection to find the common elements of two sets -
defgetCommonLetters(word1, word2):
return''.join(sorted(set(word1) & set(word2)))
& is for set intersection
.
Example/Demo -
>>>defgetCommonLetters(word1, word2):...return''.join(sorted(set(word1) & set(word2)))...>>>getCommonLetters('apple','google')
'el'
>>>getCommonLetters('microsoft','apple')
''
Solution 2:
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
>>>defgetCommonLetters(a, b):...return''.join(sorted(set(a).intersection(set(b))))...>>>getCommonLetters('google','apple')
'el'
Solution 3:
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:
defgetCommonLetters(word1, word2):
res = ""for letter in word1:
if letter in word2:
if letter notin 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.
Solution 4:
>>>''.join(sorted(set([letter for letter in word1 if letter in word2])))
Explanation:
[letter for letter in word1 if letter in word2]
: Iterate over the letters inword1
and check if the current letter is contained byword2
. If so add it to the list of common letters (with duplicates).set( 1. )
: Remove duplicates by creating a set out of the list of common letters.sorted( 2. )
: Sort the common letters (alphabetically).''.join( 3. )
: Create a string, joining the common letters by whitespaces (without duplicates).
Post a Comment for "To Get The Common Letters In Two Words Without Repetition"