Largest Number in Python

PythonServer Side ProgrammingProgramming

Suppose there is a list of non-negative integers, we have to arrange them such that they form the largest number. So if the array is [10, 2], then the largest number will be 210.

To solve this, we will follow these steps −

  • Arrange the numbers where the most significant digits are greater than place them at first, like this arrangement the numbers. After that just join the numbers from the array.

Example

Let us see the following implementation to get a better understanding −

 Live Demo

from functools import cmp_to_key
class Solution(object):
   def largestNumber(self, nums):
      for i in range(len(nums)):
         nums[i] = str(nums[i])
      nums.sort(key=cmp_to_key(lambda x,y:self.compare(x,y)))
      return "".join(nums).lstrip("0") or "0"
   def compare(self,x,y):
      if x+y<y+x:
         return 1
      elif x+y == y+x:
         return 0
      else:
         return -1
ob1 = Solution()
print(ob1.largestNumber([3,30,5,6,8]))

Input

[3,30,5,6,8]

Output

"865330"
raja
Updated on 28-Apr-2020 06:55:35

Advertisements