Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to sort all elements in a given list and merge them into a string in Python
Suppose we are given a list of positive integers. We have to sort the list in descending order and then join all the elements to form a string. The goal is to arrange numbers so that the resulting concatenated string represents the largest possible number.
So, if the input is like input = [415, 78, 954, 123, 5], then the output will be 954785415123.
Approach
To solve this, we need a custom comparison function that determines which of two numbers should come first when concatenated ?
- Define a function
cmp()that takes two parameterslandr - Compare
int(str(l) + str(r))withint(str(r) + str(l)) - Return 1 if the first combination is larger, -1 otherwise
- Sort the list using this custom comparison function
- Join all elements into a string and return it
Example
Let us see the following implementation to get better understanding ?
from functools import cmp_to_key
def cmp(l, r):
if int(str(l) + str(r)) > int(str(r) + str(l)):
return 1
else:
return -1
def solve(input_list):
input_list.sort(key=cmp_to_key(cmp), reverse=True)
return "".join(map(str, input_list))
# Test the function
numbers = [415, 78, 954, 123, 5]
result = solve(numbers)
print(f"Input: {numbers}")
print(f"Output: {result}")
Input: [415, 78, 954, 123, 5] Output: 954785415123
How It Works
The custom comparison function works by testing which concatenation produces a larger number. For example, when comparing 78 and 5:
-
str(78) + str(5) = "785"?int("785") = 785 -
str(5) + str(78) = "578"?int("578") = 578 - Since 785 > 578, number 78 should come before 5
Alternative Approach Using Lambda
You can also use a lambda function for a more concise solution ?
from functools import cmp_to_key
def solve_lambda(numbers):
numbers.sort(key=cmp_to_key(lambda x, y: 1 if int(str(x) + str(y)) > int(str(y) + str(x)) else -1), reverse=True)
return "".join(map(str, numbers))
# Test the function
numbers = [415, 78, 954, 123, 5]
result = solve_lambda(numbers)
print(f"Result: {result}")
Result: 954785415123
Conclusion
This solution uses a custom comparison function to sort numbers in a way that produces the largest possible concatenated string. The cmp_to_key function converts the comparison function to work with Python's sorting algorithm.
