Python - 比较两个句子,哪种方法是正确的?
Python - Comparing two sentences, which of these approaches is correct?
我正在努力通过 python 复习和 运行 进入以下问题,这些问题让我对如何最好地回答它有点困惑。我已经将我的解决方案和我在网上找到的解决方案放在一起,并且有兴趣了解社区认为哪个是最佳解决方案,也许我的开头是错误的:
给定两个句子,构建一个数组,其中包含出现在一个#sentence 而不是另一个#sentence 中的单词。
我的解决方案:
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
def findWords(A,B):
res = []
asplit = A.split()
bsplit = B.split()
#print(asplit)
#print(bsplit)
for item in range(len(asplit)):
if asplit[item] not in bsplit: res.append(asplit[item])
for item in range(len(bsplit)):
if bsplit[item] not in asplit: res.append(bsplit[item])
return res
findWords(A,B)
互联网解决方案:
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
d={}
for w in A.split():
if w in d:
d[w]=d.get(w,0)+1
else:
d[w]=1
for w in B.split():
if w in d:
d[w]=d.get(w,0)+1
else:
d[w]=1
unmatchedW=[w for w in d if d[w]==1]
print (unmatchedW)
这会将 A
和 B
拆分为存储在包含唯一单词的 set()
中的单词。结果等于两个集合中不同元素的list
,即集合之间的对称差,用^
运算符表示。
A = "Geeks for Geeks hello"
B = "Learning from Geeks for Geeks"
def findWords(A, B):
return list(set(A.split(' ')) ^ set(B.split(' ')))
print(findWords(A, B))
输出:
['hello', 'from', 'Learning']
我正在努力通过 python 复习和 运行 进入以下问题,这些问题让我对如何最好地回答它有点困惑。我已经将我的解决方案和我在网上找到的解决方案放在一起,并且有兴趣了解社区认为哪个是最佳解决方案,也许我的开头是错误的:
给定两个句子,构建一个数组,其中包含出现在一个#sentence 而不是另一个#sentence 中的单词。
我的解决方案:
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
def findWords(A,B):
res = []
asplit = A.split()
bsplit = B.split()
#print(asplit)
#print(bsplit)
for item in range(len(asplit)):
if asplit[item] not in bsplit: res.append(asplit[item])
for item in range(len(bsplit)):
if bsplit[item] not in asplit: res.append(bsplit[item])
return res
findWords(A,B)
互联网解决方案:
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
d={}
for w in A.split():
if w in d:
d[w]=d.get(w,0)+1
else:
d[w]=1
for w in B.split():
if w in d:
d[w]=d.get(w,0)+1
else:
d[w]=1
unmatchedW=[w for w in d if d[w]==1]
print (unmatchedW)
这会将 A
和 B
拆分为存储在包含唯一单词的 set()
中的单词。结果等于两个集合中不同元素的list
,即集合之间的对称差,用^
运算符表示。
A = "Geeks for Geeks hello"
B = "Learning from Geeks for Geeks"
def findWords(A, B):
return list(set(A.split(' ')) ^ set(B.split(' ')))
print(findWords(A, B))
输出:
['hello', 'from', 'Learning']