Open In App

Python | Maximum frequency character in String

Last Updated : 27 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article gives us the methods to find the frequency of maximum occurring character in a python string. This is quite important utility nowadays and knowledge of it is always useful. Let’s discuss certain ways in which this task can be performed. 

Method 1 : Naive method + max() 

In this method, we simply iterate through the string and form a key in a dictionary of newly occurred element or if element is already occurred, we increase its value by 1. We find maximum occurring character by using max() on values. 

Python3




# Python 3 code to demonstrate
# Maximum frequency character in String
# naive method
 
# initializing string
test_str = "GeeksforGeeks"
 
# printing original string
print ("The original string is : " + test_str)
 
# using naive method to get
# Maximum frequency character in String
all_freq = {}
for i in test_str:
 if i in all_freq:
  all_freq[i] += 1
 else:
  all_freq[i] = 1
res = max(all_freq, key = all_freq.get)
 
# printing result
print ("The maximum of all characters in GeeksforGeeks is : " + str(res))


Output : 

The original string is : GeeksforGeeks
The maximum of all characters in GeeksforGeeks is : e

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 2 : Using collections.Counter() + max() 

The most suggested method that could be used to find all occurrences is this method, this actually gets all element frequency and could also be used to print single element frequency if required. We find maximum occurring character by using max() on values. 

Python3




# Python 3 code to demonstrate
# Maximum frequency character in String
# collections.Counter() + max()
from collections import Counter
 
# initializing string
test_str = "GeeksforGeeks"
 
# printing original string
print ("The original string is : " + test_str)
 
# using collections.Counter() + max() to get
# Maximum frequency character in String
res = Counter(test_str)
res = max(res, key = res.get)
 
# printing result
print ("The maximum of all characters in GeeksforGeeks is : " + str(res))


Output : 

The original string is : GeeksforGeeks
The maximum of all characters in GeeksforGeeks is : e

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 3 : Using a dictionary

  • First, the string “GeeksforGeeks” is initialized and stored in the variable test_str.
  • An empty dictionary called freq is created. This dictionary will be used to store the frequency of each character in the string.
  • The for loop iterates over each character in the test_str string. For each character, it checks if the character already exists in the freq dictionary. If it does, the frequency count is incremented by 1. If not, a new key is added to the dictionary with a frequency count of 1.
  • After the for loop completes, the max() function is used to find the key with the maximum value in the freq dictionary. The key parameter is passed to the max() function to specify that the key with the maximum value (i.e., the character with the highest frequency) should be returned.
  • Finally, the result is printed to the console as a string.

Python3




# initializing string
test_str = "GeeksforGeeks"
 
# printing original string
print ("The original string is : " + test_str)
 
# creating an empty dictionary
freq = {}
 
# counting frequency of each character
for char in test_str:
    if char in freq:
        freq[char] += 1
    else:
        freq[char] = 1
 
# finding the character with maximum frequency
max_char = max(freq, key=freq.get)
 
# printing result
print("The maximum of all characters in GeeksforGeeks is : " + str(max_char))


Output

The original string is : GeeksforGeeks
The maximum of all characters in GeeksforGeeks is : e

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 4: Using a generator expression:

This approach uses a generator expression with the max function to find the character with the maximum frequency. The lambda function returns the frequency count for each character in the string, and the max function returns the character with the maximum frequency. This approach may be less efficient for longer strings because it has to count the frequency of each character multiple times.

Python3




test_str = "GeeksforGeeks"
res = max(test_str, key=lambda x: test_str.count(x))
print(res)


Output

e

Time Complexity: O(n)
Auxiliary Space: O(1)



Similar Reads

Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
Given a string S, the task is to find the prefix of string S with the maximum possible length such that frequency of each character in the prefix is at most the number of characters in S with minimum frequency. Examples: Input: S = 'aabcdaab' Output: aabcd Explanation: Frequency of characters in the given string - {a: 4, b: 2, c: 1, d: 1} Minimum f
8 min read
Python - Sort Strings by maximum frequency character
Given a string, the task is to write a Python program to perform sort by maximum occurring character. Input : test_list = ["geekforgeeks", "bettered", "for", "geeks"] Output : ['for', 'geeks', 'bettered', 'geekforgeeks'] Explanation : 1 < 2 < 3 < 4, is ordering of maximum character occurrence frequency. Input : test_list = ["geekforgeeks",
3 min read
Python | Frequency of each character in String
Given a string, the task is to find the frequencies of all the characters in that string and return a dictionary with key as the character and its value as its frequency in the given string. Method #1 : Naive method Simply iterate through the string and form a key in dictionary of newly occurred element or if element is already occurred, increase i
6 min read
Python | Construct string from character frequency tuple
Sometimes, while working with data, we can have a problem in which we need to perform construction of string in a way that we have a list of tuple having character and it's corresponding frequency and we require to construct a new string from that. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is brute
5 min read
Python - Sort String list by K character frequency
Given String list, perform sort operation on basis of frequency of particular character. Input : test_list = ["geekforgeekss", "is", "bessst", "for", "geeks"], K = 's' Output : ['bessst', 'geekforgeekss', 'geeks', 'is', 'for'] Explanation : bessst has 3 occurrence, geeksforgeekss has 3, and so on. Input : test_list = ["geekforgeekss", "is", "bessst
4 min read
Python - Expand Character Frequency String
Given a string, which characters followed by its frequency, create the appropriate string. Examples: Input : test_str = 'g7f2g3i2s2b3e4' Output : gggggggffgggiissbbbeeee Explanation : g is succeeded by 7 and repeated 7 times. Input : test_str = 'g1f1g1' Output : gfg Explanation : f is succeeded by 1 and repeated 1 time. Method #1: Using zip() + joi
4 min read
Python | Find frequency of given character at every position in list of lists
Given a list of lists, the task is to find the frequency of a character at every position of sub-list in list of lists. Input : lst = [['X', 'Y', 'X'], ['Z', 'Y', 'X'], ['Y', 'Y', 'Y'], ['Z', 'Z', 'X'], ['Y', 'Z', 'X']], character = 'X' Output: [0.2, 0.0, 0.8] Explanation: We have 3 elements in each sublist, we have to find position of 'X' at posit
5 min read
Python program to read character by character from a file
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it. Example Input: GeeksOutput: G e e k sExplanation: Iterated through character by character from the input as shown in the output.Read a fi
2 min read
Python - Create a Dictionary with Key as First Character and Value as Words Starting with that Character
In this article, we will code a python program to create a dictionary with the key as the first character and value as words starting with that character. Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds t
6 min read
Python | Insert character after every character pair
Sometimes, we can have a problem in which we need to insert a specific character after a pair(second) characters using Python. This kind of problem can occur while working with data, that require insertion of commas or any other special character mainly in the Machine Learning domain. Let's discuss certain ways in which this problem can be solved.
6 min read
Practice Tags :
three90RightbarBannerImg