[Tutor] finding common words using set.
Cameron Simpson
cs at cskk.id.au
Sun Jan 1 03:56:45 EST 2023
On 01Jan2023 16:41, mhysnm1964 at gmail.com <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.
>This is the first time I have delt with the set data methods and are trying
>to understand how to use them.
>
>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:])
> # 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?
When I run it I get "banana", as it is the only word in all three
strings. I'm using this code:
def find_common_words(strings):
print("strings =", strings)
# Split the strings into lists of words
word_lists = [s.split() for s in strings]
print("word_lists =", word_lists)
# Find the intersection of the sets of words
common_words = set(word_lists[0]).intersection(*word_lists[1:])
print("common_words =", common_words)
# Join the common words into a single string
return ' '.join(common_words)
find_common_words(
['apple orange banana', 'orange banana grape', 'banana mango']
)
which is just your code with some print() calls to see what's going on.
The print() calls should show you where things are going wrong, but your
code seems correct to me and seems to work here.
strings = ['apple orange banana', 'orange banana grape', 'banana mango']
word_lists = [['apple', 'orange', 'banana'], ['orange', 'banana', 'grape'], ['banana', 'mango']]
common_words = {'banana'}
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list