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
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.
>>> ''.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 in word1
and check if the current letter is contained by word2
. 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).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'
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')
''