Help needed with Strings and Conditionals (Part Two)

Hi guys,

I’m stuck at this exercise, maybe some kind soul can help me :slight_smile: https://www.codecademy.com/courses/learn-python-3/lessons/introduction-to-strings/exercises/strings-in-conditionals-ii

I really don’t understand why the solution given is this one:

def common_letters(string_one, string_two):
common =
for letter in string_one:
if (letter in string_two) and not (letter in common):
common.append(letter)
return common

More specifically, why is it

if (letter in string_two) and not (letter in common):

instead of

if (letter in string_one) and (letter in string_two): ?

I’d really appreciate your help!

Thanks

The reason for using the ´common´ array is to store the characters in common, but also to exclude duplicates.

For example:
common_letters("hellraiser", "hello")
would yield two duplicate characters:
['h', 'e', 'l', 'l', 'e']

In order to fix that we take letter from the for loop and first check if the letter is found in string_two and then we check if the letter also exists in common.
With the same example we would then get:
common_letters("hellraiser", "hello")
Yields:
['h', 'e', 'l']

I hope this helps :slight_smile:

2 Likes

Thanks! It does help actually :+1:

1 Like