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 # Python3 code to demonstrate working of # Sort by Maximum digit in Element # Using max() + sort() def max_dig(ele): # getting maximum digit by magnitude return max(str(ele)) # initializing list test_list = [234, 92, 15, 8, 721] # printing original list print("The original list is : " + str(test_list)) # calling sort fnc. to sort with key test_list.sort(key = max_dig) # printing result print("Sorted List : " + str(test_list))
OutputThe 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 # Python3 code to demonstrate working of # Sort by Maximum digit in Element # Using sorted() + lambda + max() # initializing list test_list = [234, 92, 15, 8, 721] # printing original list print("The original list is : " + str(test_list)) # lambda fnc. used to get maximum Element logic res = sorted(test_list, key = lambda ele : max(str(ele))) # printing result print("Sorted List " + str(res))
OutputThe 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 # initializing list test_list = [234, 92, 15, 8, 721] # printing original list 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) #This code is contributed by Jyothi pinjala
OutputThe 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 # Python3 code to demonstrate working of # Sort by Maximum digit in Element # Using a loop and a dictionary # initializing list test_list = [234, 92, 15, 8, 721] # printing original list print("The original list is : " + str(test_list)) # using loop and dictionary 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] # extracting numbers in ascending order of max digit res = [] for key in sorted(num_dict): res.extend(sorted(num_dict[key])) # printing result print("Sorted List " + str(res))
OutputThe 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 # Python3 code to demonstrate working of # Sort by Maximum digit in Element # Using itertools.groupby() and lambda function import itertools # initializing list test_list = [234, 92, 15, 8, 721] # printing original list print("The original list is : " + str(test_list)) # defining lambda function to convert number to list of digits num_to_digits = lambda num: [int(digit) for digit in str(num)] # sorting list by maximum digit in each number sorted_list = sorted(test_list, key=lambda num: max(num_to_digits(num))) # grouping sorted list by maximum digit sorted_groups = [list(group) for key, group in itertools.groupby(sorted_list, key=lambda num: max(num_to_digits(num)))] # flattening the groups into a single sorted list sorted_result = [num for group in sorted_groups for num in sorted(group)] # printing result print("Sorted List " + str(sorted_result))
OutputThe 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 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 and Minimum K elements in Tuple
Sometimes, while dealing with tuples, we can have problem in which we need to extract only extreme K elements, i.e maximum and minimum K elements in Tuple. This problem can have applications across domains such as web development and Data Science. Let's discuss certain ways in which this problem can
8 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 - Row with Maximum Record Element
Sometimes, while working with Python Records, we can have a problem in which we need to find the row with maximum record element. This kind of problem can come in domains of web development and day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_list = [
7 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