Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tìm cặp phần tử có hiệu lớn nhất trong Python


Cho danh sách số, tìm cặp phần tử có độ chênh lệch tuyệt đối lớn nhất.

Cách 1: nlargest từ heapq + combinations

Tạo tất cả cặp tổ hợp 2 phần tử, dùng nlargest(2, ..., key=abs diff) lấy 2 cặp hiệu lớn nhất.

from itertools import combinations
from heapq import nlargest
listA = [21, 14, 30, 11, 17, 18]
res = nlargest(2, combinations(listA, 2), key=lambda sub: abs(sub[0]-sub[1]))
print("Pairs max diff:", res)  # [(30, 11), (14, 30)]

Cách 2: combinations + max()

Dùng max() với key là hiệu tuyệt đối, trả về một cặp.

from itertools import combinations
listA = [21, 14, 30, 11, 17, 18]
res = max(combinations(listA, 2), key=lambda sub: abs(sub[0]-sub[1]))
print("Pair max diff:", res)  # (30, 11)