Me All
Me All

Reputation: 269

Finding all common letters in an unknown set of strings

I want to create a function that takes a list of strings as a parameter and that returns only those characters that are common to all strings. I want to do this using the set API.

For example:

my_words = ["house", "cheese", "helicopter"]

def FindCommonCharacters(my_words):
    xxxx

Output: {"e", "h"}

I know how to do this if I know beforehand how many strings I will have in my list. Since that way I can convert each string into a set and then use the intersection operation. But I don't know what to do if I don't know the number of strings... Any ideas?

Note: I can't use map nor asterisks (*), as I have seen in similar questions.

Upvotes: 0

Views: 67

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61930

One alternative without using * or map is the following:

from functools import reduce

my_words = ["house", "cheese", "helicopter"]

my_sets = [set(w) for w in my_words]
head, tail = my_sets[0], my_sets[1:]
result = reduce(set.intersection, tail, head)

print(result)

The above approach could be consider the functional version of this answer. Note that set.intersection is designed for more multiple sets as can be read in the documentation:

Return a new set with elements common to the set and all others.

So for the sake of completeness I include two examples below:

my_words = ["house", "cheese", "helicopter"]
result = set.intersection(*(set(s) for s in my_words))

Output

{'h', 'e'}

As commented by @Jab an alternative is to use map:

result = set.intersection(*map(set, my_words))

Upvotes: 2

SpghttCd
SpghttCd

Reputation: 10890

IIUC perhaps

my_words = ["house", "cheese", "helicopter"]

s = set(my_words[0])
for w in my_words[1:]:
    s = s.intersection(w)

# {'e', 'h'}

Upvotes: 3

Related Questions