Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python หาค่าสูงสุดอันดับ 2 ใน Dictionary

ในบทความนี้ เราจะเรียนรู้วิธีแก้ปัญหาตามข้อกำหนดด้านล่าง

ข้อกำหนดปัญหา − เราได้รับสองจำนวนเต็ม ต้องพิมพ์ค่าสูงสุดอันดับ 2 ใน Dictionary

มาสังเกตแนวคิดในการนำไปใช้ด้านล่าง

วิธีที่ 1 − ใช้ sorted() function ด้วยดัชนีลบ

ตัวอย่าง

# input example
example_dict = {"tutor": 3, "tutorials": 15, "point": 9, "tutorialspoint": 19}
# เรียงลิสต์และ取得อันดับ 2 จากท้าย
print(list(sorted(example_dict.values()))[-2])

ผลลัพธ์

15

วิธีที่ 2 − ใช้ sort method บนลิสต์แล้ว取得อันดับ 2 จากท้าย

ตัวอย่าง

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 โดยไม่ใช้ built-in function

ตัวอย่าง

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

สรุป

ในบทความนี้ เราได้เรียนรู้วิธีหาค่าสูงสุดอันดับ 2 ใน Dictionary (และลิสต์) 3 วิธี: sorted(), sort(), และ brute-force