Python - Largest number possible from list of given numbers

PythonServer Side ProgrammingProgramming

In this article, we are going to learn how to find the possible largest number from the given list of numbers. We will see two different ways to find to solve the problem. Follow the below steps to solve the problem.

  • Import the itertools module for permutations method.
  • Initialize the list with numbers and an empty list.
  • Iterate over the permutations of the list.
    • Join all the combinations and add the result to the empty list.
  • Find the max number from the result with max method and key as int.
  • Convert the string to integer and print it.

Example

Let's see the code.

 Live Demo

# importing the module
import itertools

# initializing the list
numbers = [45, 35, 138, 43, 67]

# result
result = []

# permutations
for permutation in itertools.permutations(str(number) for number in numbers):
   result.append(''.join(permutation))

# finding max
maximum = max(result, key=int)

# printing the max
print(int(maximum))

If you run the above code, then you will get the following result.

Output

67454335138

Let's see another way to solve the problem. We will sorted function to solve the problem. Follow the below steps to write the code.

  • Pass the list to the sorted function.
  • Write a function called get_key that accepts two arguments.
  • Return -1 if the str(first) + str(second) > str(second) + str(first) else 1.
  • Joining the list of elements using join method.
  • Print the result by converting into an integer.

As we are using a function as key, we have to convert it to the key using cmp_to_key method from functools. Let's see the code.

Example

 Live Demo

from functools import cmp_to_key

# initializing the list
numbers = [45, 35, 138, 43, 67]

def get_key(first, second):
   if str(first) + str(second) > str(second) + str(first):
      return -1
   return 1

# getting the result
result = sorted(numbers, key=cmp_to_key(get_key))

# joining the result
result = "".join(str(integer) for integer in result)

# printing the result
print(int(result))

If you run the above code, then you will get the following result.

Output

67454335138

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 13-Nov-2020 18:43:27
Advertisements