Cho mảng, tìm max, min, second largest, second smallest.
Thuật toán
Bước 1: Nhập phần tử list. Bước 2: Lấy một số so sánh với tất cả số khác trong list. Bước 3: Lấy max, min, second largest, second smallest.
Ví dụ mã
# Tìm largest, smallest, second largest, second smallest trong List
def maxmin(A):
maxi = A[0]
secondsmax = A[0]
mini = A[0]
secondmini = A[0]
for item in A:
if item > maxi:
maxi = item
elif secondsmax != maxi and secondsmax < item:
secondsmax = item
elif item < mini:
mini = item
elif secondmini != mini and secondmini > item:
secondmini = item
print("Largest element is ::>", maxi)
print("Second Largest element is ::>", secondsmax)
print("Smallest element is ::>", mini)
print("Second Smallest element is ::>", secondmini)
# Driver Code
A = list()
n = int(input("Enter the size of the List ::"))
print("Enter the number ::")
for i in range(int(n)):
k = int(input(""))
A.append(int(k))
maxmin(A)
Kết quả
Enter the size of the List ::6 Enter the number :: 12 30 2 34 90 67 Largest element is ::> 90 Second Largest element is ::> 67 Smallest element is ::> 2 Second Smallest element is ::> 12