Khi cần kiểm tra xem một tuple có chứa toàn bộ phần tử riêng biệt (không trùng lặp) hay không, có thể so sánh độ dài của tuple với độ dài của set tạo từ tuple đó.
set chỉ chứa phần tử duy nhất. Nếu len(set(tuple)) == len(tuple) -> không có phần tử trùng lặp.
Ví dụ
# Tuple có tất cả phần tử khác nhau
tuple_distinct = (11, 14, 54, 0, 58, 41)
print(f"Tuple: {tuple_distinct}")
is_distinct = len(set(tuple_distinct)) == len(tuple_distinct)
print(f"Có phần tử riêng biệt (distinct)? {is_distinct}")
# Tuple có phần tử trùng lặp
tuple_with_dupes = (11, 14, 54, 0, 58, 41, 11)
print(f"\nTuple có trùng: {tuple_with_dupes}")
is_distinct2 = len(set(tuple_with_dupes)) == len(tuple_with_dupes)
print(f"Có phần tử riêng biệt? {is_distinct2}")
Kết quả
Tuple: (11, 14, 54, 0, 58, 41) Có phần tử riêng biệt (distinct)? True Tuple có trùng: (11, 14, 54, 0, 58, 41, 11) Có phần tử riêng biệt? False
Giải thích
set(tuple)loại bỏ phần tử trùng lặp.- Nếu độ dài set = độ dài tuple gốc -> không có phần tử nào bị loại -> tất cả distinct.
- Nếu độ dài set < độ dài tuple -> có phần tử trùng lặp.
Hàm tái sử dụng
def is_distinct(seq):
"""Kiểm tra sequence có tất cả phần tử unique không."""
return len(seq) == len(set(seq))
# Test
print(is_distinct((1, 2, 3))) # True
print(is_distinct((1, 2, 2))) # False
print(is_distinct('hello')) # False (l, l trùng)
print(is_distinct('world')) # True
Tìm phần tử trùng lặp cụ thể
from collections import Counter
def find_duplicates(tup):
"""Trả về dict {phần tử: số lần} cho các phần tử xuất hiện > 1 lần."""
counts = Counter(tup)
return {k: v for k, v in counts.items() if v > 1}
t = (11, 14, 0, 78, 33, 11, 10, 78, 0)
print(find_duplicates(t)) # {11: 2, 78: 2, 0: 2}
Kiểm tra distinct cho nested tuple
nested = ((1, 2), (3, 4), (1, 2))
# Tuple chứa tuple -> có thể hash -> set hoạt động
print(is_distinct(nested)) # False
# Nếu chứa list (unhashable) -> lỗi TypeError
# mixed = ((1, 2), [3, 4], (1, 2)) # set(mixed) -> TypeError
# Cách xử lý: chuyển list -> tuple trước
def is_distinct_mixed(seq):
def make_hashable(x):
if isinstance(x, list):
return tuple(x)
return x
normalized = tuple(make_hashable(x) for x in seq)
return len(normalized) == len(set(normalized))