How to use itertools and reduce methods In Python
Algorithm :
- Split the two input sentences into lists of words.
- Compute the set intersection of the two lists to find common words.
- Filter out the common words from both sentences.
- Print the remaining words in each sentence.
import itertools
from functools import reduce
def removeCommonWords(sent1, sent2):
sent1 = list(sentence1.split())
sent2 = list(sentence2.split())
common_words = set(sent1).intersection(sent2)
sent1 = list(filter(lambda x: x not in common_words, sent1))
sent2 = list(filter(lambda x: x not in common_words, sent2))
print(*sent1)
print(*sent2)
sentence1 = "sky is blue in color"
sentence2 = "raj likes sky blue color"
removeCommonWords(sentence1, sentence2)
#This code is contributed by Jyothi pinjala.
Output
is in raj likes
The time complexity: O(n^2) because of the nested loop of the set intersection operation, where n is the length of the longest sentence. The filter function has a linear time complexity of O(n) in the worst case, where n is the length of the input list.
The space complexity: O(n) because we are creating two separate lists for each sentence, and potentially creating a set that could be as large as the length of the longest sentence.
Python program to remove words that are common in two Strings
Given two strings S1 and S2, representing sentences, the task is to print both sentences after removing all words which are present in both sentences.
Input: S1 = “sky is blue in color”, S2 =”Raj likes sky blue color “
Output: is in
Raj likes
Explanation: The common words are [ sky, blue, color ]. Removing these words from the two sentences modifies the sentences to the specified output.Input: S1 = “learn data structures and algorithms in w3wiki“, S2 = “w3wiki is the computer science portal for Geeks“
Output: learn data structures and algorithms in
is the computer science portal for.
Table of Content
- Using Hashing
- Using Sets and Lists
- Using Lists and remove()
- Using Operator.countOf() function
- Using itertools and reduce methods
- Using List Comprehension and Filter
Contact Us