Python - Arrange given Numbers to form Minimum Number


Arrange given Numbers to form Minimum Number

In this problem, we are given a list of numbers from user via console input. We have to arrange these numbers such that the resulting number is the minimum number possible.

The solution is to sort the given list of numbers in increasing order based on the first digit of these numbers, and then join them.

Program

In the following program, we read a list of numbers from user separated by space. Since the user provides them as a string, we can just split the string into chunks of numbers and sort them as strings lexicographically in ascending order. After that, we join them and print the result. We may also convert this into an integer, if required.

Also, we trim any leading zeros for the numbers after splitting the input string.

Python Program

#read input
n = input()
#split input for individual numbers
n_list = n.split(' ')
#trim any leading zeroes
n_list = [x.lstrip('0') for x in n_list]
#sort in ascending order lexicographically
n_list.sort()
#join the numbers
minimum = ''.join(n_list)
#convert to integer
minimum = int(minimum)
#print result
print(minimum)

Output #1

52 01 25 6
125526

Output #2

22 6 32 28 96
222832696

Output #2

1 4 0 2 3 0058 690
123458690

Reference tutorials for the above program

Summary

In this Python Tutorial, we learned how to re-arrange given numbers to form the smallest possible number.