Python - Sort Strings by maximum frequency character
Last Updated :
10 Apr, 2023
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", "for", "geeks"]
Output : ['for', 'geeks', 'geekforgeeks']
Explanation : 1 < 2 < 4, is ordering of maximum character occurrence frequency.
Method #1 : Using sort() + Counter() + max()
In this, we perform inplace sorting using sort(), and Counter() is used to compute characters frequency, max() used to get maximum of computed frequencies.
Python3
# Python3 code to demonstrate working of
# Sort Strings by maximum frequency character
# Using sort() + Counter() + max()
from collections import Counter
# getting maximum character frequency
def max_freq(arg_str):
res = Counter(arg_str)
return arg_str.count(max(res, key = res.get))
# initializing list
test_list = ["geekforgeeks", "bettered", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
test_list.sort(key = max_freq)
# printing result
print("Sorted List : " + str(test_list))
Output:
The original list is : ['geekforgeeks', 'bettered', 'for', 'geeks']
Sorted List : ['for', 'geeks', 'bettered', 'geekforgeeks']
Method #2 : Using sorted() + lambda + Counter()
In this, we perform the task of performing sort using sorted(), and lambda function to get a single statement logical expression, avoiding external function call.
Python3
# Python3 code to demonstrate working of
# Sort Strings by maximum frequency character
# Using sorted() + lambda + Counter()
from collections import Counter
# getting maximum character frequency
def max_freq(arg_str):
res = Counter(arg_str)
return arg_str.count(max(arg_str, key = arg_str.get))
# initializing list
test_list = ["geekforgeeks", "bettered", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
# lambda function to drive logic
res = sorted(test_list,
key = lambda arg_str : arg_str.count(
max(Counter(arg_str), key = Counter(arg_str).get)))
# printing result
print("Sorted List : " + str(res))
Output:
The original list is : ['geekforgeeks', 'bettered', 'for', 'geeks']
Sorted List : ['for', 'geeks', 'bettered', 'geekforgeeks']
The time and space complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)
Using dictionary and sorting:
Approach:
In this approach, we first create a dictionary that stores the count of the most occurring character for each string. Then, we sort the list based on the values of this dictionary. If two or more strings have the same count of the most occurring character, we sort them based on their original order in the input list.
Python3
def max_char_freq(string):
freq_dict = {}
for s in string:
max_char = max(set(s), key=s.count)
freq_dict[s] = s.count(max_char)
return freq_dict
def sort_by_max_freq(string_list):
freq_dict = max_char_freq(string_list)
return sorted(string_list, key=lambda x: (freq_dict[x], string_list.index(x)))
test_list = ["geekforgeeks", "bettered", "for", "geeks"]
print(sort_by_max_freq(test_list)) # Output: ['for', 'geeks', 'bettered', 'geekforgeeks']
Output['for', 'geeks', 'bettered', 'geekforgeeks']
Time Complexity: O(nlogn) where n is the length of the input list
Space Complexity: O(n)
Similar Reads
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. I
4 min read
Maximum Frequency Character in String - Python The task of finding the maximum frequency character in a string involves identifying the character that appears the most number of times. For example, in the string "hello world", the character 'l' appears the most frequently (3 times).Using collection.CounterCounter class from the collections modul
3 min read
Python - Sort by Rear Character in Strings List Given a String list, perform sort by the rear character in the Strings list. Input : test_list = ['gfg', 'is', 'for', 'geeks'] Output : ['gfg', 'for', 'is', 'geeks'] Explanation : g < r < s = s, hence the order. Input : test_list = ['gfz', 'is', 'for', 'geeks'] Output : ['for', 'is', 'geeks',
5 min read
Python - Least Frequent Character in String The task is to find the least frequent character in a string, we count how many times each character appears and pick the one with the lowest count.Using collections.CounterThe most efficient way to do this is by using collections.Counter which counts character frequencies in one go and makes it eas
3 min read
Python - Sort Matrix by Maximum String Length Given a matrix, perform row sort basis on the maximum length of the string in it. Input : test_list = [['gfg', 'best'], ['geeksforgeeks'], ['cs', 'rocks'], ['gfg', 'cs']] Output : [['gfg', 'cs'], ['gfg', 'best'], ['cs', 'rocks'], ['geeksforgeeks']] Explanation : 3 < 4 < 5 < 13, maximum leng
3 min read
Specific Characters Frequency in String List-Python The task of counting the frequency of specific characters in a string list in Python involves determining how often certain characters appear across all strings in a given list.For example, given a string list ["geeksforgeeks"] and a target list ['e', 'g'], the output would count how many times 'e'
4 min read
Python - Sort Strings by Maximum ASCII value Given strings list, perform sort by Maximum Character in String. Input : test_list = ["geeksforgeeks", "is", "best", "cs"] Output : ["geeksforgeeks", "is", "cs", "best"] Explanation : s = s = s < t, sorted by maximum character. Input : test_list = ["apple", "is", "fruit"] Output : ["apple", "is",
4 min read
Kth most frequent Character in a given String Given a string str and an integer K, the task is to find the K-th most frequent character in the string. If there are multiple characters that can account as K-th most frequent character then, print any one of them.Examples: Input: str = "GeeksforGeeks", K = 3 Output: f Explanation: K = 3, here 'e'
6 min read
Python - Sort Matrix by total characters Given a String Matrix, sort by total data, i.e total characters in each row. Input : test_list = [["Gfg", "is", "Best"], ["Geeksforgeeks", "Best"], ["ILvGFG"]] Output : [['ILvGFG'], ['Gfg', 'is', 'Best'], ['Geeksforgeeks', 'Best']] Explanation : 6 < 11 < 17 total characters respectively after
5 min read
Python - All substrings Frequency in String Given a String, extract all unique substrings with their frequency. Input : test_str = "ababa" Output : {'a': 3, 'ab': 2, 'aba': 2, 'abab': 1, 'ababa': 1, 'b': 2, 'ba': 2, 'bab': 1, 'baba': 1} Explanation : All substrings with their frequency extracted. Input : test_str = "GFGF" Output : {'G': 2, 'G
5 min read