100 XP

84. Largest number from parts

Advanced sorting strings

Write a function largest_number(numbers) that takes a list of whole numbers, 0 or more, and arranges them side by side, in some order, to make the largest number possible. Return it as a string, since it can be very long.

  • Every number is used once, and none is broken up: 10 and 2 make "210", not "201".
  • If every number is 0 the result is "0", not "00".

Sorting the numbers from biggest down doesn't work (it gives "102" for 10 and 2), and neither does sorting their text, which puts "5" before "56". Compare two parts by trying both orders: which of a + b and b + a, as text, is bigger?

Example 1

Inputnumbers = [10, 2]
Output"210"
Explanation"2" + "10" beats "10" + "2".

Example 2

Inputnumbers = [5, 50, 56]
Output"56550"
Explanation56 first; then 5 before 50, as 550 > 505.

Example 3

Inputnumbers = [0, 0]
Output"0"
ExplanationAll zeros: written once.

Constraints

  • numbers has 1 to 100 whole numbers, each from 0 to 10^9.

Submit also runs 11 more tests you can't see.

Practises Modules and Imports (lesson 22).

Code
def largest_number(numbers):
    """Arrange numbers side by side to make the largest.

    numbers: list of int, each 0 or more, at least one
    Returns: str, the largest number they make, written
        in full ("0" if they are all 0)
    """
    # Write your code here
    pass