# Uncommon Words from Two Sentences using Python

Finding uncommon words in two sentences is one of the problems in coding interviews. In this problem, you have to find all the words that appear only once in two given sentences. So, if you want to know how to find uncommon words in two sentences, this article is for you. In this article, I’ll take you through how to solve the problem of finding Uncommon Words from Two Sentences using Python.

## Finding Uncommon Words from Two Sentences

A word is considered uncommon if it occurs exactly once in one of the sentences and does not appear in the other. To solve this problem, you need to find all the words that appear only once in two given sentences.

Here’s an example of the input and output values of this problem:

• sentence 1 = “the quick brown fox jumps over the lazy dog”,
• sentence 2 = “the quick brown dog jumps over the lazy fox”
• Output: [‘fox’, ‘dog’]

In the example above, the uncommon words in these two sentences are “fox” and “dog” since they appear exactly once in each sentence and do not appear in the other.

## Finding Uncommon Words from Two Sentences Using Python

I hope you have understood what the Uncommon Words problem means. Now here’s how to solve this problem using Python:

```def uncommonFromSentences(s1, s2):
words1 = s1.split()
words2 = s2.split()

counts = {}
for word in words1 + words2:
counts[word] = counts.get(word, 0) + 1

uncommon = [word for word in counts if counts[word] == 1]
return uncommon

s1 = "this apple is sweet"
s2 = "this apple is sour"
print(uncommonFromSentences(s1, s2))```
`Output: ['sweet', 'sour']`

The function first splits the input sentences s1 and s2 into individual words using the built-in split() function. It then creates a dictionary (‘counts’) to track the number of occurrences of each word in the two sentences. This is done using a for loop that iterates through each word in both word1 and word2 and updates the corresponding count in the numbers using the .get() method.

The function then creates a list (‘uncommon’) containing only the words that appear exactly once in s1 or s2. It is done using a list comprehension that checks the count of each word in ‘counts’.

### Summary

A word is considered “uncommon” if it occurs exactly once in one of the sentences and does not appear in the other. To solve this problem, you need to find all the words that appear only once in two given sentences. I hope you liked this article on solving the Uncommon Words problem using Python. You can find more Python practice questions for coding interviews here. Feel free to ask valuable questions in the comments section below. ##### Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1534