Given a string, the task is to find the character that appears the most number of times along with its count. For example:
Input: geeksforgeeks
Output: ('e', 4)
Let’s explore different methods in Python to solve this problem efficiently.
Using collections.Counter()
The Counter() class from the collections module counts how many times each character appears in a string. Then, we use the most_common(1) method to get the character with the highest frequency.
from collections import Counter
s = "geeksforgeeks"
count = Counter(s)
res = count.most_common(1)[0]
print(res)
Output
('e', 4)
Explanation:
- Counter(s) returns a dictionary-like object with characters as keys and their counts as values.
- most_common(1) gives a list of the top 1 most frequent character.
- [0] extracts that tuple from the list.
Using Dictionary and max() Function
This method manually creates a frequency dictionary and finds the character with the maximum count using max() with a key argument.
s = "geeksforgeeks"
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
res = max(freq, key=freq.get)
print(res, freq[res])
Output
e 4
Explanation:
- freq.get(ch, 0) + 1 increments the count of each character.
- max(freq, key=freq.get) finds the key (character) with the highest value (count).
Using Two Lists
In this method, one list stores unique characters, and the other stores their counts using the built-in count() method.
s = "geeksforgeeks"
a = []
b = []
for ch in s:
if ch not in a:
a.append(ch)
b.append(s.count(ch))
res = max(b)
ele = a[b.index(res)]
print(ele, res)
Output
e 4
Explanation:
- a keeps track of unique characters.
- s.count(ch) returns how many times each character appears.
- The index of the maximum value in b gives the most frequent character from a.
Using operator.countOf() Function
This method uses the operator.countOf() function to count occurrences of each character instead of the string method .count().
import operator
s = "geeksforgeeks"
a = []
b = []
for ch in s:
if ch not in a:
a.append(ch)
b.append(operator.countOf(s, ch))
res = max(b)
ele = a[b.index(res)]
print(ele, res)
Output
e 4
Explanation:
- operator.countOf(s, ch) counts occurrences of ch in s.
- Works similar to count() but comes from the operator module.