ในบทความนี้ เราจะเรียนรู้วิธีแก้ปัญหาตามข้อกำหนดด้านล่าง
ข้อกำหนดปัญหา − เราได้รับลิสต์ ต้องแสดงตัวเลขใหญ่เป็นอันดับ 2 ในลิสต์
มี 3 วิธีแก้ปัญหา
วิธีที่ 1 − ใช้ set() function และ remove() function
ตัวอย่าง
list1 = [11, 22, 1, 2, 5, 67, 21, 32] # 取得 unique elements new_list = set(list1) # ลบสมาชิกมากที่สุดออกจาก list1 new_list.remove(max(new_list)) # คำนวณ max element ด้วย built-in method print(max(new_list))
ผลลัพธ์
32
วิธีที่ 2 − ใช้ sort() method และดัชนีลบ
ตัวอย่าง
list1 = [11, 22, 1, 2, 5, 67, 21, 32]
# ใช้ built-in sort method
list1.sort()
# อันดับ 2 จากท้าย
print("Second largest element in the list is:", list1[-2])
ผลลัพธ์
Second largest element in the list is: 32
วิธีที่ 3 − ใช้ brute-force method หา max อันดับ 2
ตัวอย่าง
list1 = [11, 22, 1, 2, 5, 67, 21, 32]
# สมมติ max_ เท่ากับ max ของ index 0 และ 1 และ secondmax คือ min ระหว่างพวกเขา
max_ = max(list1[0], list1[1])
secondmax = min(list1[0], list1[1])
for i in range(2, len(list1)):
# ถ้าพบสมาชิกมากกว่า max_
if list1[i] > max_:
secondmax = max_
max_ = list1[i]
# ถ้าพบสมาชิกมากกว่า secondmax
else:
if list1[i] > secondmax:
secondmax = list1[i]
print("Second highest number in the list is:", str(secondmax))
ผลลัพธ์
Second highest number in the list is: 32
สรุป
ในบทความนี้ เราได้เรียนรู้ 3 วิธีหาตัวเลขใหญ่อันดับ 2 ในลิสต์: set+remove, sort+negative index, brute-force