92.6k views
2 votes
Create a function named common_letters(strings) that returns the intersection of letters among a list of strings. The parameter is a list of strings. For example, you can find the common letter in the domains/words statistics, computer science, and biology.

User Zanegray
by
4.1k points

1 Answer

1 vote

Answer:

The solution code is written in Python 3:

  1. letterList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
  2. 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
  3. def common_letters(strings):
  4. result = []
  5. for l in letterList:
  6. count = 0
  7. for s in strings:
  8. if l in s:
  9. count = count + 1
  10. if(count == len(strings)):
  11. result.append(l)
  12. return result
  13. print(common_letters(["statistics", "computer science", "biology"]))
  14. print(common_letters(["apple", "orange", "grape"]))

Step-by-step explanation:

Firstly, we can create a letter list that includes the letters from a to z.

Next we create a function common_letters that take one parameter (Line 4).

Create a result list to hold the output the function (Line 5).

Next, we create a for-loop to traverse through each of the letter in the letterList and then create another for loop to traverse through every single string in the input strings and then check if the letter found in a current string. If so increment the count by one. (Line 7 -11).

Logically if the number of occurrence of a single letters equal to number of words in the strings list, this means the letter is common to all the words (Line 13). We can append this letter, l, to result list (Line 14) and return it as the output (Line 16).

We can test the functions using two sample word list (Line 18-19) and the output is as follows:

['i']

['a', 'e']

User Ebuzer Taha KANAT
by
4.5k points