FAQ: Introduction to Strings - Strings and Conditionals (Part Two)

If the variable names are any indication of what is expected, why would be call it with,

contains('big', 'bigger')?

The arguments don’t match the parameters.

contains('bigger', 'big')

and,

return little_string in big_string

Hello. I am new to posting questions. I have made fairly good progress until I arrived at this section, specifically related to question 2.

Question 2:
“Write a function called common_letters that takes two arguments, string_one and string_two and then returns a list with all of the letters they have in common.”

The solution I proposed has 2 components to it.

First it will look to see if a character from ‘string_one’ is found in ‘string_two’. If this is true, it will append that character to en empty list. So this first part may result in duplicate characters depending on the strings under evaluation.

Second a conditional will check to see if each character within a string is greater in count than 1 (this means the character is duplicated within the list) if so, it will remove that character.

When I run the code, my list captures a character that is not shared between both strings. My guess is that something carries over from when the exercise checks the solutions. I have checked the proposed solution on Jupyter and it appears to work just fine.

Proposed solution:

lst1 = []
def common_letters(string_one, string_two):
  for i in string_two:
    if i in string_one:
      lst1.append(i)
  for j in lst1:
    if lst1.count(j) > 1:
      del lst1[lst1.index(j)]
  return lst1

I have tried to reverse the logic to pick a character from ‘string_1’ and see if its in ‘string_2’, and the same error message results. I have also tried using:

pop()

But the same error message results

Here is the error message:

Expected the test common_letters('python', 'ruby on rails') to return [‘y’, ‘o’, ‘n’], instead got [‘a’, ‘y’, ‘o’, ‘n’].

Update - an hour later… I have identified a solution… this doesn’t seem elegant… why should I have to look for errors, when the code should work? Nevertheless see below:

lst1 = []
def common_letters(string_one, string_two):
  for i in string_one:
    if i in string_two:
      lst1.append(i)
  for j in lst1:
    if lst1.count(j) > 1:
      lst1.pop(lst1.index(j))
 # for k in lst1:
 #   if k in string_two:
 #     print(k)
 #   else:
 #     lst1.pop(lst1.index(k))
  for k in lst1:
    if k in string_one:
      continue
    else:
      lst1.pop(lst1.index(k))
  return lst1