Skip to content

Commit cc4337d

Browse files
authored
Create sentence-similarity.py
1 parent 044f7b4 commit cc4337d

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Python/sentence-similarity.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Time: O(n + p)
2+
# Space: O(p)
3+
4+
# Given two sentences words1, words2 (each represented as an array of strings),
5+
# and a list of similar word pairs pairs, determine if two sentences are similar.
6+
#
7+
# For example, "great acting skills" and "fine drama talent" are similar,
8+
# if the similar word pairs are pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]].
9+
#
10+
# Note that the similarity relation is not transitive.
11+
# For example, if "great" and "fine" are similar, and "fine" and "good" are similar,
12+
# "great" and "good" are not necessarily similar.
13+
#
14+
# However, similarity is symmetric.
15+
# For example, "great" and "fine" being similar is the same as "fine" and "great" being similar.
16+
#
17+
# Also, a word is always similar with itself.
18+
# For example, the sentences words1 = ["great"], words2 = ["great"], pairs = [] are similar,
19+
# even though there are no specified similar word pairs.
20+
#
21+
# Finally, sentences can only be similar if they have the same number of words.
22+
# So a sentence like words1 = ["great"] can never be similar to words2 = ["doubleplus","good"].
23+
#
24+
# Note:
25+
# - The length of words1 and words2 will not exceed 1000.
26+
# - The length of pairs will not exceed 2000.
27+
# - The length of each pairs[i] will be 2.
28+
# - The length of each words[i] and pairs[i][j] will be in the range [1, 20].
29+
30+
class Solution(object):
31+
def areSentencesSimilar(self, words1, words2, pairs):
32+
"""
33+
:type words1: List[str]
34+
:type words2: List[str]
35+
:type pairs: List[List[str]]
36+
:rtype: bool
37+
"""
38+
if len(words1) != len(words2): return False
39+
lookup = set(map(tuple, pairs))
40+
return all(w1 == w2 or (w1, w2) in lookup or (w2, w1) in lookup \
41+
for w1, w2 in itertools.izip(words1, words2))

0 commit comments

Comments
 (0)