Given a list of sentences ‘sentence’ and a list of words ‘words’, write a Python program to find which sentence in the list of sentences consist of all words contained in ‘words’ and return them within a list.
Examples:
Input : sentence = ['I love tea', 'He hates tea', 'We love tea'] words = ['love', 'tea'] Output : ['I love tea', 'We love tea'] Input : sentence = ['python coder', 'geeksforgeeks', 'coder in geeksforgeeks'] words = ['coder', 'geeksforgeeks'] Output : ['coder in geeksforgeeks']
Approach #1 : Using List comprehension
We first use list comprehension, to return a boolean value for each substring of the list of sentence and store it in ‘res’. Finally, return a list comprising of the desired sentences according to the boolean values in ‘res’.
# Python3 program to Check if given words # appear together in a list of sentence def check(sentence, words): res = [ all ([k in s for k in words]) for s in sentence] return [sentence[i] for i in range ( 0 , len (res)) if res[i]] # Driver code sentence = [ 'python coder' , 'geeksforgeeks' , 'coder in geeksforgeeks' ] words = [ 'coder' , 'geeksforgeeks' ] print (check(sentence, words)) |
['coder in geeksforgeeks']
Approach #2 : List comprehension (Alternative way)
For each substring in list of sentences, it checks how many words are there in the current substring and stores it in a variable ‘k’. If the length of ‘k’ matches with length of list of words, just append it to ‘res’.
# Python3 program to Check if given words # appear together in a list of sentence def check(sentence, words): res = [] for substring in sentence: k = [ w for w in words if w in substring ] if ( len (k) = = len (words) ): res.append(substring) return res # Driver code sentence = [ 'python coder' , 'geeksforgeeks' , 'coder in geeksforgeeks' ] words = [ 'coder' , 'geeksforgeeks' ] print (check(sentence, words)) |
['coder in geeksforgeeks']
Approach #3 : Python map()
map()
method applies a function on list of sentences and check if all words are contained in the list or not by splitting the list of words. It returns a boolean value for each substring of the list of sentence and store it in ‘res’. Finally, repeat the same steps as in approach #1.
# Python3 program to Check if given words # appear together in a list of sentence def check(sentence, words): res = list ( map ( lambda x: all ( map ( lambda y:y in x.split(), words)), sentence)) return [sentence[i] for i in range ( 0 , len (res)) if res[i]] # Driver code sentence = [ 'python coder' , 'geeksforgeeks' , 'coder in geeksforgeeks' ] words = [ 'coder' , 'geeksforgeeks' ] print (check(sentence, words)) |
['coder in geeksforgeeks']
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.