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
Python program to find the most occurring character and its count
In this article, we will learn how to find the most occurring character in a string and count its occurrences using Python's Counter class.
Problem Statement
Given an input string, we need to find the character that appears most frequently and return both the character and its count.
Approach
Create a dictionary using Counter method having characters as keys and their frequencies as values.
Find the maximum occurrence count and get the corresponding character.
Using Counter from collections
The Counter class provides an easy way to count character frequencies ?
from collections import Counter
def find_most_frequent(input_string):
# Count character frequencies
char_count = Counter(input_string)
# Find the character with maximum count
most_frequent_char = max(char_count, key=char_count.get)
max_count = char_count[most_frequent_char]
return most_frequent_char, max_count
# Driver program
if __name__ == "__main__":
input_string = 'Tutorialspoint'
char, count = find_most_frequent(input_string)
print(f"Most frequent character: '{char}' appears {count} times")
The output of the above code is ?
Most frequent character: 't' appears 3 times
Alternative Method Using Dictionary
You can also solve this without using Counter ?
def find_most_frequent_manual(input_string):
# Create dictionary to store character counts
char_count = {}
# Count each character
for char in input_string:
char_count[char] = char_count.get(char, 0) + 1
# Find character with maximum count
most_frequent_char = max(char_count, key=char_count.get)
max_count = char_count[most_frequent_char]
return most_frequent_char, max_count
# Test the function
input_string = 'Tutorialspoint'
char, count = find_most_frequent_manual(input_string)
print(f"Most frequent character: '{char}' appears {count} times")
print(f"Character frequencies: {dict(sorted(char_count.items()))}")
Most frequent character: 't' appears 3 times
Character frequencies: {'T': 1, 'a': 1, 'i': 2, 'l': 1, 'n': 2, 'o': 2, 'p': 1, 'r': 1, 's': 1, 't': 3, 'u': 1}
How It Works
The Counter method creates a dictionary where:
Keys: Individual characters from the string
Values: Frequency count of each character
The max() function with key=char_count.get finds the character with the highest frequency count.
Conclusion
Using Counter from collections is the most efficient way to find the most frequent character. The max() function with a key parameter easily identifies the character with the highest count.
