Common Words in Two Strings in Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings s0 and s1, they are representing a sentence, we have to find the number of unique words that are shared between these two sentences. We have to keep in mind that, the words are case-insensitive so "tom" and "ToM" are the same word.

So, if the input is like s0 = "i love python coding", s1 = "coding in python is easy", then the output will be 2 as there are 2 common words, ['python', 'coding']

To solve this, we will follow these steps −

  • convert s0 and s1 into lowercase
  • s0List := a list of words in s0
  • s1List := a list of words in s1
  • convert set from words in s0List and s1List, then intersect them to get common words, and return the count of the intersection result.

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s0, s1):
      s0 = s0.lower()
      s1 = s1.lower()
      s0List = s0.split(" ")
      s1List = s1.split(" ")
   return len(list(set(s0List)&set(s1List)))
ob = Solution()
S = "i love python coding"
T = "coding in python is easy"
print(ob.solve(S,T))

Input

"i love python coding", "coding in python is easy"

Output

2
raja
Published on 22-Sep-2020 11:03:23
Advertisements