Counting Number of Dinosaurs in Python


Suppose we have a string called animals and another string called dinosaurs. Every letter in animals represents a different type of animal and every unique character in dinosaurs string represents a different dinosaur. We have to find the total number of dinosaurs in animals.

So, if the input is like animals = "xyxzxyZ" dinosaurs = "yZ", then the output will be 3, as there are two types of dinosaurs y and Z, in the animal string there are two y type animal and one Z type animal.

To solve this, we will follow these steps −

  • res := 0
  • dinosaurs := a new set by taking elements from dinosaurs
  • for each c in dinosaurs, do
    • res := res + occurrence of c in animals
  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

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))

Input

"xyxzxyZ", "yZ"

Output

3

Updated on: 22-Sep-2020

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements