'''
给定两个句子 A 和 B 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)
如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。
返回所有不常用单词的列表。
您可以按任何顺序返回列表。
示例 1:
输入:A = "this apple is sweet", B = "this apple is sour"
输出:["sweet","sour"]
示例 2:
输入:A = "apple apple", B = "banana"
输出:["banana"]
提示:
0 <= A.length <= 200
0 <= B.length <= 200
A 和 B 都只包含空格和小写字母
'''
import copy
class Solution:
def uncommonFromSentences(self, A, B):
"""
:type A: str
:type B: str
:rtype: List[str]
"""
la=A.split()
lb = B.split()
la_n = self._get_lc(la)
lb_n = self._get_lc(lb)
C = []
for i in la_n:
if i not in lb:
C.append(i)
else:
pass
for i in lb_n:
if i not in la:
C.append(i)
else:
pass
return list(set(C))
def _get_lc(self,la):#返回一个新的数组,去除出现2次以上的单词
ll = copy.deepcopy(la)
for i in set(ll):
if ll.count(i) > 1:
while i in ll:
ll.remove(i)
else:
pass
return ll
if __name__ == '__main__':
A="s z z z s"
B="s z ejt"
Solution = Solution()
print(Solution.uncommonFromSentences(A,B))
方法二
import copy
class Solution:
def uncommonFromSentences(self, A, B):
"""
:type A: str
:type B: str
:rtype: List[str]
"""
la=A.split()
lb = B.split()
la_n = self._get_lc(la)
lb_n = self._get_lc(lb)
sa = set(la_n)
sb = set(lb_n)
return list((sb -set(la)) |(sa-set(lb)))
def _get_lc(self,la):#返回一个新的数组,去除出现2次以上的单词
ll = copy.deepcopy(la)
for i in set(ll):
if ll.count(i) > 1:
while i in ll:
ll.remove(i)
else:
pass
return ll
if __name__ == '__main__':
A="s z z z s"
B="s z ejt"
Solution = Solution()
print(Solution.uncommonFromSentences(A,B))