84. Largest number from parts
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
numbers = [10, 2]"210"Example 2
numbers = [5, 50, 56]"56550"Example 3
numbers = [0, 0]"0"Constraints
numbershas 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).
- Work with the numbers as strings. For two of them,
ashould come first exactly whena + b > b + a: both are the same length, so comparing the strings compares the numbers. sorted()needs a key, not a comparison.functools.cmp_to_key(compare)turns a function returning -1 (a first), 1 (b first) or 0 into one.- After sorting, join the parts. If the first part is
"0", every part is, so return"0".
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.