Counting occurrences of a character in a string means counting all substrings of a character from the input string. This is one of the important questions you are asked in the coding interviews. In this article, I’ll walk you through how to count character occurrences using Python.
Count Character Occurrences using Python:
To count the occurrences of a character, we need to write an algorithm that returns the number of times each character appears in the input string. The algorithm must iterate through each character from the beginning to count the number of times each character appears in the string. Here’s how to write an algorithm for counting character occurrences using Python:
def count_characters(s):
count = {}
for i in s:
if i in count:
count[i] += 1
else:
count[i] = 1
print(count)
print(count_characters("This is a count occurrences program"))
Output:
{'T': 1, 'h': 1, 'i': 2, 's': 3, ' ': 5, 'a': 2, 'c': 4, 'o': 3, 'u': 2, 'n': 2, 't': 1, 'r': 4, 'e': 2, 'p': 1, 'g': 1, 'm': 1}
In the code above, we step through each character in the input string. If the character is already present in the string, we simply increment the value of the character by 1 and so on. Otherwise, we just add the character in the dictionary and set it to 1. In the end, we get a dictionary with the characters as keys and their values as the number of times they appeared in the string.
Summary
Counting the occurrences of a character is an important question for the coding interview. Here we have to write an algorithm to count the number of times each character appears in a string. I hope you liked this article on how to count character occurrences using Python. Feel free to ask your valuable questions in the comments section below.
Top comments (0)