# [Tutor] finding common words using set.

Alan Gauld alan.gauld at yahoo.co.uk
Sun Jan 1 04:08:04 EST 2023

```On 01/01/2023 05:41, mhysnm1964 at gmail.com wrote:

> I have created a function to find the common words within a list of strings.
> I never get any results back of the common words and cannot understand why.

> def find_common_words(strings):
>
>     # Split the strings into lists of words
>      word_lists = [s.split() for s in strings]

>     # Find the intersection of the sets of words
>     common_words = set(word_lists[0]).intersection(*word_lists[1:])

This should find the common elements across all 3 lists.
But there is only one common word: banana. (orange is
only common to two lists not all three)

>     # Join the common words into a single string
>     return ' '.join(common_words)
>
>
>
> strings = ['apple orange banana', 'orange banana grape', 'banana mango']
> common_words = find_common_words(strings)
> print(common_words)

> Should return banana orange and I get a null string. Any ideas why?

And this works for me. Are you sure you posted the exact code you ran?
Also did you insert print statements after each assignment to check the
results were what you expected? Or try it at the >>>. Here is my session:

>>> strs = ['one two three', 'two three four', 'one three five']
>>> wl = [s.split() for s in strs]
>>> wl
[['one', 'two', 'three'], ['two', 'three', 'four'], ['one', 'three',
'five']]
>>> set(wl[0])
{'two', 'one', 'three'}
>>> set(wl[0]).intersection(*wl[1:])
{'three'}
>>> res = set(wl[0]).intersection(*wl[1:])
>>> ' '.join(res)
'three'
>>>

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

```