ในบทความนี้ เราจะเรียนรู้เกี่ยวกับวิธีแก้ปัญหาตามที่ระบุด้านล่าง
แจ้งปัญหา − เราได้รับจำนวนเต็มสองจำนวน เราจำเป็นต้องพิมพ์ค่าสูงสุดที่สองในพจนานุกรม
ทีนี้มาดูแนวคิดในการใช้งานด้านล่างกัน:
แนวทางที่ 1 − การใช้ฟังก์ชัน sorted() ตามดัชนีเชิงลบ
ตัวอย่าง
#input
example_dict ={"tutor":3, "tutorials":15,
"point":9,"tutorialspoint":19}
# sorting the given list and get the second last element
print(list(sorted(example_dict.values()))[-2]) ผลลัพธ์
15
แนวทางที่ 2 - ที่นี่เราใช้วิธีการจัดเรียงในรายการแล้วเข้าถึงองค์ประกอบที่ใหญ่เป็นอันดับสอง
ตัวอย่าง
list1 = [11,22,1,2,5,67,21,32]
# using built-in sort method
list1.sort()
# second last element
print("Second largest element in the list is:", list1[-2]) ผลลัพธ์
Second largest element in the list is: 32
แนวทางที่ 3 - ที่นี่เราใช้วิธีเดรัจฉานโดยไม่ต้องใช้ฟังก์ชันในตัว
ตัวอย่าง
list1 = [11,22,1,2,5,67,21,32]
#assuming max_ is equal to maximum of element at 0th and 1st index
and secondmax is the minimum among them
max_=max(list1[0],list1[1])
secondmax=min(list1[0],list1[1])
for i in range(2,len(list1)):
# if found element is greater than max_
if list1[i]>max_:
secondmax=max_
max_=list1[i]
#if found element is greator than secondmax
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
บทสรุป
ในบทความนี้ เราได้เรียนรู้เกี่ยวกับวิธีการหาค่าสูงสุดอันดับสองในพจนานุกรม )