Python - Sort by a particular digit count in elements
Last Updated :
08 Mar, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputThe 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.
Similar Reads
Python - Sort by Maximum digit in Element
Given a List of Elements, sort by the maximum digit of the element present in the List. Input : test_list = [234, 92, 8, 721] Output : [234, 721, 8, 92] Explanation : 4 < 7 < 8 < 9, sorted by maximum digits. Input : test_list = [92, 8, 721] Output : [721, 8, 92] Explanation : 7 < 8 <
6 min read
Python Program to sort rows of a matrix by custom element count
Given Matrix, the following program shows how to sort rows of a matrix by the count of presence of numbers from a specified list. Input : test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]], cus_list = [4, 5, 7] Output : [[9, 8, 2], [6, 5], [7, 1], [4, 5, 1, 7]] Explanation : 0 < 1 = 1 < 3 i
5 min read
Python - Check if list contain particular digits
Given a List and some digits, the task is to write a python program to check if the list contains only certain digits. Input : test_list = [435, 133, 113, 451, 134], digs = [1, 4, 5, 3] Output : True Explanation : All elements are made out of 1, 4, 5 or 3 only.Input : test_list = [435, 133, 113, 451
14 min read
Python - Sort Matrix by Palindrome count
Given a String Matrix of N characters, sort each row by the count of the palindromic string in it. Input : test_list = [["nitin", "meem", "geeks"], ["peep"], ["gfg", "is", "best"], ["sees", "level", "mom", "noon"]] Output : [['peep'], ['gfg', 'is', 'best'], ['nitin', 'meem', 'geeks'], ['sees', 'leve
8 min read
Python - List Elements with given digit
Given list of elements and a digit K, extract all the numbers which contain K digit. Input : test_list = [56, 72, 875, 9, 173], K = 5 Output : [56, 875] Explanation : 56 and 875 has "5" as digit, hence extracted. Input : test_list = [56, 72, 875, 9, 173], K = 4 Output : [] Explanation : No number ha
6 min read
Python - Sort by Factor count
Given element list, sort by factor count of each element. Input : test_list = [12, 100, 22] Output : [22, 12, 100] Explanation : 3, 5, 8 factors respectively of elements. Input : test_list = [6, 11] Output : [11, 6] Explanation : 1, 4 factors respectively of elements. Method #1 : Using sort() + len(
4 min read
Python - Reform K digit elements
Given the Python list, reform the element to have K digits in a single element. Input : test_list = [223, 67, 332, 1, 239, 2, 931], K = 2 Output : [22, 36, 73, 32, 12, 39, 29, 31] Explanation : Elements reformed to assign 2 digits to each element. Input : test_list = [223, 67, 3327], K = 3 Output :
3 min read
Python | List Element Count with Order
Sometimes, while working with lists or numbers we can have a problem in which we need to attach with each element of list, a number, which is the position of that element's occurrence in that list. This type of problem can come across many domains. Let's discuss a way in which this problem can be so
4 min read
Python - Match Kth number digit in list elements
Sometimes we may face a problem in which we need to find a list if it contains numbers at the Kth index with the same digits. This particular utility has an application in day-day programming. Letâs discuss certain ways in which this task can be achieved. Method #1 : Using list comprehension + map()
7 min read
Python - Average digits count in a List
Given a list of elements extract the average digit count in List. Input : test_list = [34, 2345, 23, 456, 2, 23, 456787] Output : 2.857142857142857 Explanation : Average of all digit count. [2+4+2+3+1+2+6 = 20, 20/7 = 2.857142857142857] Input : test_list = [34, 1, 456]Output : 2.0 Explanation : Aver
4 min read