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 have to join all the elements in it to form a string. We return the joined string.

So, if the input is like input = [415, 78, 954, 123, 5], then the output will be 954785415123

To solve this, we will follow these steps −

  • Define a function cmp() . This will take l, r
    • if integer value of (string representation of (l) + string representation of (r)) > integer value of (string representation of (r) + string representation of (l)), then
      • return 1
    • otherwise,
      • return -1
  • sort the list input according to the function compare
  • join all the elements in input 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):
   input.sort(key=cmp_to_key(cmp), reverse=True)
   return "".join(map(str, input))

print(solve([415, 78, 954, 123, 5]))

Input

[415, 78, 954, 123, 5]

Output

954785415123

Updated on: 16-Oct-2021

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements