Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 animals and one Z type animal.
Algorithm
To solve this, we will follow these steps ?
- Initialize result counter as 0
- Convert dinosaurs string to a set to get unique dinosaur types
- For each unique dinosaur character, count its occurrences in animals string
- Add the count to result and return the total
Example
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, animals, dinosaurs):
result = 0
dinosaurs = set(dinosaurs)
for char in dinosaurs:
result += animals.count(char)
return result
# Test the solution
ob = Solution()
animals = "xyxzxyZ"
dinosaurs = "yZ"
print(ob.solve(animals, dinosaurs))
The output of the above code is ?
3
How It Works
The solution works by first converting the dinosaurs string into a set to eliminate duplicate characters. Then for each unique dinosaur type, we count how many times it appears in the animals string using the count() method and add it to our result.
Alternative Approach Using Collections
We can also solve this using Python's collections.Counter for a more Pythonic approach ?
from collections import Counter
def count_dinosaurs(animals, dinosaurs):
animal_count = Counter(animals)
dinosaur_types = set(dinosaurs)
total = 0
for dinosaur in dinosaur_types:
total += animal_count[dinosaur]
return total
# Test the solution
animals = "xyxzxyZ"
dinosaurs = "yZ"
print(count_dinosaurs(animals, dinosaurs))
The output of the above code is ?
3
Conclusion
Both approaches efficiently count dinosaurs by first identifying unique dinosaur types and then summing their occurrences in the animals string. The Counter approach is more efficient for large strings as it counts characters only once.
