在 Python 中統計恐龍數量


假設我們有一個稱為 animals 的字串和另一個稱為 dinosaurs 的字串。animals 中的每個字母都表示不同型別的動物,而 dinosaurs 字串的每一個唯一字元都表示一個不同的恐龍。我們必須找出 animals 中恐龍的總數。

因此,如果輸入為:animals = "xyxzxyZ" dinosaurs = "yZ",則輸出將為 3,因為在恐龍字串中存在兩種型別的恐龍 y 和 Z,而在動物字串中存在兩種型別的 y 和一種型別的 Z。

為了解決這個問題,我們將按照以下步驟進行−

  • res := 0
  • dinosaurs := 透過從恐龍中獲取元素建立的新集合
  • 對於恐龍中的每一個 c,執行
    • res := res + c 在動物中的出現次數
  • return res

讓我們看看以下實現,以便更好地理解−

示例

 即時演示

class Solution:
   def solve(self, animals, dinosaurs):
      res = 0
      dinosaurs = set(dinosaurs)
      for c in dinosaurs:
         res += animals.count(c)
      return res
ob = Solution()
animals = "xyxzxyZ"
dinosaurs = "yZ"
print(ob.solve(animals, dinosaurs))

輸入

"xyxzxyZ", "yZ"

輸出

3

更新時間:2020-09-22

168 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告