Open In App

Python – Sort String list by K character frequency

Last Updated : 01 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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”], K = ‘e’ 
Output : [“geekforgeekss”, “bessst”, “is”] 
Explanation : Ordered decreasing order of ‘e’ count. 

Method #1 : Using sorted() + count() + lambda

In this, sorted() is used to perform task of sort, count() is as function upon which sorting is to be performed. using additional key param, and function encapsulation used is lambda.

Python3




# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using sorted() + count() + lambda
 
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 'e'
 
# "-" sign used to reverse sort
res = sorted(test_list, key = lambda ele: -ele.count(K))
 
# printing results
print("Sorted String : " + str(res))


Output

The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Sorted String : ['geekforgeeks', 'geeks', 'best', 'is', 'for']

Time Complexity: O(nlogn), where n is the length of the input list. 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”. 

Method #2 : Using sort() + count() + lambda

In this, we perform task of sort using sort(), this is similar to above, only difference being that sorting is done inplace.

Python3




# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using sort() + count() + lambda
 
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 'e'
 
# "-" sign used to reverse sort
# inplace sort
test_list.sort(key = lambda ele: -ele.count(K))
 
# printing results
print("Sorted String : " + str(test_list))


Output

The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Sorted String : ['geekforgeeks', 'geeks', 'best', 'is', 'for']

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

Method #3 : Using operator.countOf() method

Python3




# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using operator.countOf()
import operator as op
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 'e'
 
# "-" sign used to reverse sort
res = sorted(test_list, key = lambda ele: -op.countOf(ele,K))
 
# printing results
print("Sorted String : " + str(res))


Output

The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Sorted String : ['geekforgeeks', 'geeks', 'best', 'is', 'for']

Time Complexity: O(NLogN)
Auxiliary Space: O(N)

Method 4: Using heapq.nlargest() and count()

Step-by-step approach:

  • Use the nlargest() function from the heapq module to return the n largest elements from a list of strings, sorted in descending order by the count of the target character K in each string. Set n to the length of the test_list to return all elements.
  • Define a lambda function that takes a string as input and returns the count of the target character K in that string.
  • Use the count() method to count the number of occurrences of K in each string in the test_list.
  • Use the sorted() function to sort the test_list based on the count of K in each string. The key parameter of sorted() should be the lambda function defined in step 2.
  • Return the sorted list of strings.

Python3




import heapq
 
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
 
# initializing K
K = 'e'
 
# define lambda function to count occurrences of K in a string
count_K = lambda s: s.count(K)
 
# use nlargest to sort test_list based on count of K in each string
n = len(test_list)
sorted_list = heapq.nlargest(n, test_list, key=count_K)
 
# use sorted to sort test_list based on count of K in each string
sorted_list = sorted(test_list, key=count_K, reverse=True)
 
# print results
print("Sorted String: ", sorted_list)


Output

Sorted String:  ['geekforgeeks', 'geeks', 'best', 'is', 'for']

Time complexity: O(n*log(n)) for sorting the list of strings.
Auxiliary space: O(n) for storing the list of strings.



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 | 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 | 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 | Maximum frequency character in String
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
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 | Sort list elements by frequency
Given a list containing repeated and non-repeated elements, the task is to sort the given list on basis of the frequency of elements. Let's discuss few methods for the same. Method #1: Using collections.counter() C/C++ Code # Python code to demonstrate # sort list by frequency # of elements from collections import Counter ini_list = [1, 2, 3, 4, 4,
4 min read
Python | Sort given list by frequency and remove duplicates
Problems associated with sorting and removal of duplicates is quite common in development domain and general coding as well. The sorting by frequency has been discussed, but sometimes, we even wish to remove the duplicates without using more LOC's and in a shorter way. Let's discuss certain ways in which this can be done. Method #1 : Using count()
5 min read
Python - Sort by Frequency of second element in Tuple List
Given list of tuples, sort by frequency of second element of tuple. Input : test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] Output : [(1, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)] Explanation : 7 occurs 3 times as 2nd element, hence all tuples with 7, are aligned first. Input : test_list = [(1, 7), (8, 7), (9, 8), (3, 7)] Output : [(
6 min read
three90RightbarBannerImg