Bài toán: cho danh sách, hiển thị số lớn thứ 2.
Cách 1: Dùng set() và remove()
Loại trùng lặp bằng set(), xóa phần tử lớn nhất bằng remove(max()), rồi max() lần 2.
list1 = [11, 22, 1, 2, 5, 67, 21, 32] new_list = set(list1) new_list.remove(max(new_list)) print(max(new_list))
32
Cách 2: Dùng sort() và chỉ mục âm
list1 = [11, 22, 1, 2, 5, 67, 21, 32]
list1.sort()
print("Second largest element in the list is:", list1[-2])
Second largest element in the list is: 32
Cách 3: Brute-force duyệt một lần
list1 = [11, 22, 1, 2, 5, 67, 21, 32]
max_ = max(list1[0], list1[1])
secondmax = min(list1[0], list1[1])
for i in range(2, len(list1)):
if list1[i] > max_:
secondmax = max_
max_ = list1[i]
else:
if list1[i] > secondmax:
secondmax = list1[i]
print("Second highest number is the list is:", str(secondmax))
Second highest number is the list is: 32
Kết luận
Đã học 3 cách tìm số lớn thứ 2 trong list.