Software engineering and personal development

Tag: count

How to Quickly Count the Number of Times an Element Appears in a Tuple in Python

In Python, a tuple is an ordered and immutable collection of elements. Tuples are often used to store related pieces of information together, such as the x and y coordinates of a point, or the name and age of a person. Sometimes, we may need to count the number of times a particular element appears in a tuple. Python provides a built-in method called count() that makes it easy to accomplish this task. In this article, we will explore how to use the count() method to count the number of times an element appears in a tuple.

The count() method is a built-in method in Python that returns the number of times a specified element appears in a tuple. The method takes a single argument, which is the element to be counted. Here’s an example:

my_tuple = ('a', 1, 'f', 'a', 5, 'a')
print(my_tuple.count('a'))  # 3
Continue reading

How to Quickly Check if 2 Strings Are Anagrams using Counter

Anagrams are strings that have the same letters but in a different order for example abc, bca, cab, acb, bac are all anagrams, since they all contain the same letters.

We can check whether two strings are anagrams in Python in different ways. One way to do that would be to use Counter from the collections module.

From the documentation:

 A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

In plain English, with Counter, we can get a dictionary that represents the frequency of elements in a list. Let us see this in an example:

 from collections import Counter
 ​
 print(Counter("Hello"))  # Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})

Now we can use Counter to quickly check whether two strings are anagrams or not:

 from collections import Counter
 ​
 ​
 def check_if_anagram(first_string, second_string):
     first_string = first_string.lower()
     second_string = second_string.lower()
     return Counter(first_string) == Counter(second_string)
 ​
 ​
 print(check_if_anagram('testinG', 'Testing'))  # True
 print(check_if_anagram('Here', 'Rehe'))  # True
 print(check_if_anagram('Know', 'Now'))  # False

We can also check whether 2 strings are anagrams using sorted():

 def check_if_anagram(first_word, second_word):
     first_word = first_word.lower()
     second_word = second_word.lower()
     return sorted(first_word) == sorted(second_word)
 ​
 print(check_if_anagram("testinG", "Testing"))  # True
 print(check_if_anagram("Here", "Rehe"))  # True
 print(check_if_anagram("Know", "Now"))  # False

That’s basically it.

I hope you find this useful.

© 2024 Fatos Morina

Theme by Anders NorenUp ↑