-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharrange_list_nums_to_largest_num.py
More file actions
50 lines (37 loc) · 1.27 KB
/
Copy patharrange_list_nums_to_largest_num.py
File metadata and controls
50 lines (37 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
'''
Given a list of numbers, create an algorithm that arranges them in order to form
the largest possible integer. For example, given [10, 7, 76, 415],
you should return 77641510
'''
from functools import cmp_to_key
def compare(x, y):
# Compare two numbers by their concatenated strings in both possible orders
if x + y > y + x:
return -1
elif x + y < y + x:
return 1
else:
return 0
def largest_number(numbers):
# Convert the numbers to strings
str_numbers = list(map(str, numbers))
print(str_numbers)
# Sort the numbers based on the custom comparison function
sorted_numbers = sorted(str_numbers, key=cmp_to_key(compare))
print(sorted_numbers)
# Concatenate the sorted numbers
largest_num = ''.join(sorted_numbers)
# Convert to integer and back to string to remove leading zeros
return str(int(largest_num))
numbers = [10, 7, 76, 415]
print(largest_number(numbers))
'''
from functools import cmp_to_key
# List to be sorted
numbers = [5, 2, 4, 3, 1]
# Convert the comparison function to a key function
key_func = cmp_to_key(my_compare)
# Use the key function with sorted()
sorted_numbers = sorted(numbers, key=key_func)
print(sorted_numbers)
'''