Python 程式來查詢兩個字串中不常見的字詞


在本文中,我們將瞭解如下內容的問題陳述的解決方案。

問題陳述 - 給定兩個字串,我們需要從此字串中獲取不常見的字詞。

現在讓我們觀察如下實現中的解決方案 -

示例

 現場演示

# uncommon words
def find(A, B):
   # count
   count = {}
   # insert in A
   for word in A.split():
      count[word] = count.get(word, 0) + 1
   # insert in B
   for word in B.split():
      count[word] = count.get(word, 0) + 1
   # return ans
   return [word for word in count if count[word] == 1]
# main
A = "Tutorials point "
B = "Python on Tutorials point"
print("The uncommon words in strings are:",find(A, B))

輸出

The uncommon words in strings are: ['Python', 'on']

所有變數都在區域性範圍內宣告,並且在上圖中可見其引用的物件。

結論

在本文中,我們已經瞭解了我們如何編寫 Python 程式來查詢兩個字串中的不常見字詞

更新於: 20-Dec-2019

622 次檢視

開啟您的職業生涯

透過完成課程獲得認證

入門
廣告
© . All rights reserved.