Python program to find the most occurring character and its count
Last Updated :
15 Mar, 2023
Given a string, write a python program to find the most occurrence character and its number of occurrences. Examples:
Input : hello
Output : ('l', 2)
Input : geeksforgeeks
Output : ('e', 4)
We can solve this problem quickly in python using Counter() method. Simple Approach is to 1) Create a dictionary using Counter method having strings as keys and their frequencies as values. 2) Find the maximum occurrence of a character i.e. value and get the index of it.
Python
from collections import Counter
def find_most_occ_char( input ):
wc = Counter( input )
s = max (wc.values())
i = wc.values().index(s)
print wc.items()[i]
if __name__ = = "__main__":
input = 'geeksforgeeks'
find_most_occ_char( input )
|
Output:
('e', 4)
Time Complexity: O(N) where N is the length of the input string
Auxiliary Space: O(1)
One more approach to find the most occurring character and its count in python3
Python3
string1 = "geeksforgeeks"
list1 = []
list2 = []
for i in string1:
if i not in list1:
list1.append(i)
list2.append(string1.count(i))
occ = max (list2)
ele = list1[list2.index(occ)]
print (ele,occ)
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach : Using operator.countOf() and index() methods
Python3
string1 = "geeksforgeeks"
list1 = []
list2 = []
for i in string1:
if i not in list1:
list1.append(i)
import operator
list2.append(operator.countOf(string1,i))
occ = max (list2)
ele = list1[list2.index(occ)]
print (ele,occ)
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach: Using lambda function
This new approach uses a lambda function to count the occurrences of each character in the string, and then creates a list of tuples containing the character and its count. Finally, it finds the tuple with the maximum count and prints its character and counts.
Python3
string1 = "geeksforgeeks"
count_char = lambda c: string1.count(c)
char_counts = [(c, count_char(c)) for c in set (string1)]
most_common = max (char_counts, key = lambda x: x[ 1 ])
print (most_common[ 0 ], most_common[ 1 ])
|
Time Complexity: O(N*N), due to count() function used in the lambda
Auxiliary Space: O(N), for creating a list of tuples containing the character and its count.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...