Open In App

Python – Sort by a particular digit count in elements

Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of elements, sort by K digit in each element.

Examples:

Input : test_list = [4322, 2122, 123, 1344], K = 2 
Output : [1344, 123, 4322, 2122] 
Explanation : 0 < 1 < 2 < 3, sorted by count of 2 in each element.

Input : test_list = [4322, 2122, 1344], K = 2 
Output : [1344, 4322, 2122] 
Explanation : 0 < 2 < 3, sorted by count of 2 in each element. 

Method #1: Using list comprehension + str() + count()

In this, we perform the task of sorting using sort(), and the task of finding frequency is done using count().

Python3




# Python3 code to demonstrate working of
# Sort by digit count in elements
# Using list comprehension + count() + str()
 
def count_dig(ele):
     
    # returning digit count
    return str(ele).count(str(K))
 
# initializing list
test_list = [4322, 2122, 123, 1344]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# calling external sort
test_list.sort(key = count_dig)
 
# printing result
print("Sorted list : " + str(test_list))


Output

The original list is : [4322, 2122, 123, 1344]
Sorted list : [1344, 123, 4322, 2122]

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

Method #2 : Using sorted() + str() + count() + lambda

In this, we perform the task of performing sort using sorted(), and use the lambda function to get sort logic rather than the external function.

Python3




# Python3 code to demonstrate working of
# Sort by digit count in elements
# Using sorted() + str() + count() + lambda
 
# initializing list
test_list = [4322, 2122, 123, 1344]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# sorting using sorted()
# not inplace sort.
res = sorted(test_list, key = lambda ele : str(ele).count(str(K)))
 
# printing result
print("Sorted list : " + str(res))


Output

The original list is : [4322, 2122, 123, 1344]
Sorted list : [1344, 123, 4322, 2122]

Time Complexity: O(n*logn), where n is the length of the input list. This is because we’re using the built-in sorted() function which has a time complexity of O(nlogn) in the worst case.
Auxiliary Space: O(1), as we’re not using any additional space other than the input list itself. 

Method #3 : Using count(),sort(),extend() and index() methods

Python3




# Python3 code to demonstrate working of
# Sort by digit count in elements
 
# initializing list
test_list = [4322, 2122, 123, 1344]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
x=[]
for i in test_list:
    x.append(str(i).count(str(K)))
y=[]
y.extend(x)
y.sort()
res=[]
for i in y:
    res.append(test_list[x.index(i)])
 
# printing result
print("Sorted list : " + str(res))


Output

The original list is : [4322, 2122, 123, 1344]
Sorted list : [1344, 123, 4322, 2122]

Method 4:  using operator.countOf() method

Python3




# Python3 code to demonstrate working of
# Sort by digit count in elements
import operator as op
 
# initializing list
test_list = [4322, 2122, 123, 1344]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# sorting using sorted()
# not inplace sort.
res = sorted(test_list, key = lambda ele : op.countOf(str(ele),str(K)))
 
# printing result
print("Sorted list : " + str(res))


Output

The original list is : [4322, 2122, 123, 1344]
Sorted list : [1344, 123, 4322, 2122]

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

Method 5:Using the itertools.groupby() function

Python3




import itertools
test_list = [4322, 2122, 123, 1344]
K = 2
test_list.sort(key = lambda x: str(x).count(str(K)))
sorted_list = [list(g) for k, g in itertools.groupby(test_list, key = lambda x: str(x).count(str(K)))]
print(sorted_list)
#This code is contributed by Vinay Pinjala.


Output

[[1344], [123], [4322], [2122]]

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

Method 6:Using a dictionary : 

Algorithm:

1.Create an empty dictionary to store the numbers with their frequency of digit ‘K’.
2.Iterate through the input list and for each number in the list:
a. Convert the number to string.
b. Count the frequency of digit ‘K’ in the string.
c. Add the number to the dictionary with its frequency of digit ‘K’ as key.
3.Sort the dictionary based on keys (i.e. frequency of digit ‘K’).
4.Create a list of lists where each sub-list contains all the numbers having the same frequency of digit ‘K’.
5.Return the list of lists.

Python3




def group_numbers_by_frequency_using_dict(test_list, K):
    # Create an empty dictionary to store the numbers with their frequency of digit 'K'
    dict_freq = {}
    # Iterate through the input list and for each number in the list:
    for num in test_list:
        # Convert the number to string
        num_str = str(num)
        # Count the frequency of digit 'K' in the string
        freq = num_str.count(str(K))
        # Add the number to the dictionary with its frequency of digit 'K' as key
        if freq in dict_freq:
            dict_freq[freq].append(num)
        else:
            dict_freq[freq] = [num]
    # Sort the dictionary based on keys (i.e. frequency of digit 'K')
    dict_freq_sorted = dict(sorted(dict_freq.items()))
    # Create a list of lists where each sub-list contains all the numbers having the same frequency of digit 'K'
    res = [dict_freq_sorted[key] for key in dict_freq_sorted]
    # Return the list of lists
    return res
 
# Test the function
test_list = [4322, 2122, 123, 1344]
K = 2
print(group_numbers_by_frequency_using_dict(test_list, K))  # Output: [[123], [4322, 1344], [2122]]
#This code is contributed by Jyothi pinjala.


Output

[[1344], [123], [4322], [2122]]

Time Complexity: O(n * m * log m), where n is the number of elements in the input list and m is the maximum number of digits in an element of the input list.
Auxiliary Space: O(n), where n is the number of elements in the input list.



Last Updated : 08 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads