Python – Sort by Maximum digit in Element
Last Updated :
15 May, 2023
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 < 9, sorted by maximum digits.
Method #1 : Using max() + sort()
In this, we perform task of inplace sort using sort() and maximum element is extracted using max().
Python3
def max_dig(ele):
return max ( str (ele))
test_list = [ 234 , 92 , 15 , 8 , 721 ]
print ( "The original list is : " + str (test_list))
test_list.sort(key = max_dig)
print ( "Sorted List : " + str (test_list))
|
Output
The original list is : [234, 92, 15, 8, 721]
Sorted List : [234, 15, 721, 8, 92]
Time Complexity: O(nlogn+m)
Auxiliary Space: O(1)
Method #2 : Using sorted() + lambda + max()
In this, we use sorted() perform non-inplace sort, and avoid usage of external function using lambda function to get maximum digit.
Python3
test_list = [ 234 , 92 , 15 , 8 , 721 ]
print ( "The original list is : " + str (test_list))
res = sorted (test_list, key = lambda ele : max ( str (ele)))
print ( "Sorted List " + str (res))
|
Output
The original list is : [234, 92, 15, 8, 721]
Sorted List [234, 15, 721, 8, 92]
Time Complexity: O(n*nlogn) where n is the number of elements in the list “test_list”. sorted() + lambda + max() performs n*nlogn number of operations.
Auxiliary Space: O(1), no extra space is required
Method #3 : Using a list comprehension with sorted():
1.Define the list of integers to be sorted.
2.Define a key function that takes an integer element and returns the maximum digit in the element.
3.Apply the sorted() function to the list, using the key function to determine the sorting order.
4.Print the resulting sorted list.
Python3
test_list = [ 234 , 92 , 15 , 8 , 721 ]
print ( "The original list is : " + str (test_list))
result = sorted (test_list, key = lambda x: max ([ int (d) for d in str (x)]))
print (result)
|
Output
The original list is : [234, 92, 15, 8, 721]
[234, 15, 721, 8, 92]
Time complexity: O(d n log n), where d is the maximum number of digits in the list and n is the length of the list. In this case, the maximum number of digits is 3, since the maximum element is 721, which has 3 digits. Therefore, the time complexity is O(3 n log n), which simplifies to O(n log n).
Auxiliary space: O(n), since the key function creates a list of digits for each element and the sorted() function creates a new sorted list.
Method #5: Using a loop and a dictionary
Iterate through the list of numbers and for each number, you can extract the maximum digit and use it as a key to store the number in a dictionary. Finally, you can extract the numbers from the dictionary in ascending order of the maximum digit.
Step-by-step approach:
- Define an empty dictionary to store the numbers.
- Iterate through the list of numbers.
- For each number, convert it to a string and extract the maximum digit using the max() function.
- Check if the maximum digit already exists as a key in the dictionary. If it does, append the number to the list of numbers already stored under that key. If it doesn’t,
- Create a new key with the maximum digit and store the number as a list under that key.
- Extract the keys of the dictionary in ascending order.
- Iterate through the keys and extract the numbers stored under each key in the order they were added to the dictionary.
- Return the sorted list of numbers.
Python3
test_list = [ 234 , 92 , 15 , 8 , 721 ]
print ( "The original list is : " + str (test_list))
num_dict = {}
for num in test_list:
max_digit = max ( str (num))
if max_digit in num_dict:
num_dict[max_digit].append(num)
else :
num_dict[max_digit] = [num]
res = []
for key in sorted (num_dict):
res.extend( sorted (num_dict[key]))
print ( "Sorted List " + str (res))
|
Output
The original list is : [234, 92, 15, 8, 721]
Sorted List [234, 15, 721, 8, 92]
Time complexity: O(n log n), where n is the length of the list.
Auxiliary space: O(n), where n is the length of the list.
Method #7: Using itertools.groupby() and lambda function
- Import the itertools module.
- Define a lambda function to convert an integer to a list of its digits.
- Initialize a sorted() function that takes test_list as input and a key parameter that is set to the lambda function, which will sort the list by the maximum digit in each number.
- Use itertools.groupby() to group the sorted_list by their maximum digit.
- Extract the elements from each group and append them to a new list.
- Print the sorted list.
Python3
import itertools
test_list = [ 234 , 92 , 15 , 8 , 721 ]
print ( "The original list is : " + str (test_list))
num_to_digits = lambda num: [ int (digit) for digit in str (num)]
sorted_list = sorted (test_list, key = lambda num: max (num_to_digits(num)))
sorted_groups = [ list (group) for key, group in itertools.groupby(sorted_list, key = lambda num: max (num_to_digits(num)))]
sorted_result = [num for group in sorted_groups for num in sorted (group)]
print ( "Sorted List " + str (sorted_result))
|
Output
The original list is : [234, 92, 15, 8, 721]
Sorted List [234, 15, 721, 8, 92]
Time Complexity: O(n log n), where n is the length of test_list.
Auxiliary Space: O(n), where n is the length of test_list, due to the creation of the sorted_list and sorted_groups variables.
Similar Reads
Python - Sort by a particular digit count in elements
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, 212
5 min read
Python - Sort dictionary by max/min element in value list
Given dictionary, perform sort on basis of maximum or minimum element present in dictionary values list. Input : test_dict = {"Gfg" : [6, 4], "best" : [8, 4], "for" : [7, 13], "geeks" : [15, 5]} Output : {'geeks': [15, 5], 'for': [7, 13], 'best': [8, 4], 'Gfg': [6, 4]} Explanation : Max of values is
4 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
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 program to Sort Matrix by Maximum Row element
Given a Matrix, sort rows by maximum element. Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted. Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]
4 min read
Python - Maximum element in Cropped List
Sometimes, while working with Python, we can have a problem in which we need to get maximum of list. But sometimes, we need to get this for between custom indices. This can be need of any domain be it normal programming or web development. Let's discuss certain ways in which this task can be perform
4 min read
Python - Sort by Units Digit in List
Given a Integer list, sort by unit digits. Input : test_list = [76, 434, 23, 22342] Output : [22342, 23, 434, 76] Explanation : 2 < 3 < 4 < 6, sorted by unit digits. Input : test_list = [76, 4349, 23, 22342] Output : [22342, 23, 76, 4349] Explanation : 2 < 3 < 6 < 9, sorted by unit
7 min read
Python - Maximum element till K value
One of the problem that is basically a subproblem for many complex problems, finding maximum number till a certain number in list in python, is commonly encountered and this particular article discusses possible solutions to this particular problem. Method #1 : Naive method The most common way this
3 min read
Python program to Sort Tuples by their Maximum element
Given a Tuple List sort tuples by maximum element in a tuple. Input : test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)] Output : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)] Explanation : 19 > 7 = 7 > 2, is order, hence reverse sorted by maximum element. Input : test_list
5 min read
Python - K Maximum elements with Index in List
GIven a List, extract K Maximum elements with their indices. Input : test_list = [5, 3, 1, 4, 7, 8, 2], K = 2 Output : [(4, 7), (5, 8)] Explanation : 8 is maximum on index 5, 7 on 4th. Input : test_list = [5, 3, 1, 4, 7, 10, 2], K = 1 Output : [(5, 10)] Explanation : 10 is maximum on index 5. Method
4 min read