Python program to print sorted number formed by merging all elements in array


When it is required to print the sorted numbers that are formed by merging the elements of an array, a method can be defined that first sorts the number and converts the number to an integer. Another method maps this list to a string, and is sorted again.

Example

Below is a demonstration of the same

def get_sorted_nums(my_num):

   my_num = ''.join(sorted(my_num))
   my_num = int(my_num)
   print(my_num)

def merged_list(my_list):

   my_list = list(map(str, my_list))
   my_str = ''.join(my_list)
   get_sorted_nums(my_str)

my_list = [7, 845, 69, 60, 99, 11]
print("The list is :")
print(my_list)
print("The result is :")
merged_list(my_list)

Output

The list is :
[7, 845, 69, 60, 99, 11]
The result is :
11456678999

Explanation

  • A method named ‘get_sorted_nums’ is defined that takes a number as a parameter.

  • It is first converted to a string and then sorted.

  • Next, it is converted back to an integer and displayed on the console.

  • Another method named ‘merged_list’ is defined that takes a list as a parameter.

  • It is converted into a string using the ‘map’ method and then converted to a list.

  • The previous method to sort and convert to integer is again called by passing this string.

  • Outside the method, a list is defined and is displayed on the console.

  • The method is called by passing this parameter.

  • The output is displayed on the console.

Updated on: 21-Sep-2021

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements