-1

I came across a question which goes like this:
Given a list of strings, find the number of letters common to ALL elements. For example

mylist = ['abcdde',
          'baccd',
          'eeabg']

Required output: 2 Since only the letters 'a' and 'b' are common to all elements.
My logic was to somehow use set intersection to find the common elements. But I am not able to write code that can perform this.
Can someone please help. I would also like to have any other logic which can achieve the task more efficiently (if any).
Thanks

Dev5
  • 449
  • 3
  • 15

2 Answers2

4

You can convert each string to a set to find the unique elements, then use set.intersection to find the common elements among all the sets.

>>> set.intersection(*(set(i) for i in mylist))
{'a', 'b'}

To fully answer your question, you would then use len to find the number of elements in that resulting set

>>> len(set.intersection(*(set(i) for i in mylist)))
2
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
3

You can divide the list into sets and find the intersection using that:

sets_list = [{letter for letter in string} for string in mylist]

print(set.intersection(*sets_list))

Here, you first use list comprehension to construct a list of sets and then pass those sets into the set.intersection function will which will return the required value.

Bhavye Mathur
  • 1,024
  • 1
  • 7
  • 25
  • The code worked but you have some types and case problems. this is the output: [{'d', 'c', 'e', 'b', 'a'}, {'b', 'd', 'c', 'a'}, {'b', 'a', 'g', 'e'}] {'b', 'a'} . set_list should be sets_list and myList should be mylist – Golden Lion Sep 23 '20 at 14:28
  • Ahh, my mistake. it's been fixed :) – Bhavye Mathur Sep 23 '20 at 15:58