Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - หาเลขที่ใหญ่ที่สุดจากการเรียงตัวเลขในลิสต์

หาการเรียงลำดับตัวเลขในลิสต์ที่ต่อกันได้เลขใหญ่สุด

วิธีที่ 1: ใช้ itertools.permutations (Brute Force)

import itertools

numbers = [45, 35, 138, 43, 67]
result = []

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

maximum = max(result, key=int)
print(int(maximum))  # 67454335138

วิธีที่ 2: ใช้ sorted กับ Custom Comparator (มีประสิทธิภาพมากกว่า)

from functools import cmp_to_key

numbers = [45, 35, 138, 43, 67]

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

result = sorted(numbers, key=cmp_to_key(get_key))
result = ''.join(str(n) for n in result)
print(int(result))  # 67454335138

สรุป

วิธี sorted + comparator เร็วกว่า O(n log n) เทียบกับ O(n!) ของ permutations