หาคำที่มีความถี่เป็นอันดับ 2 มากที่สุดในลิสต์คำ โดยใช้ Counter เรียงค่าความถี่
อัลกอริทึม
- สร้าง Counter จากลิสต์คำ
- เรียงค่าความถี่มากไปน้อย
- หาค่าอันดับ 2 (index 1)
- หา key ที่มีค่านั้น
โค้ดตัวอย่าง
from collections import Counter
def secondrepeatation(A):
con = Counter(A)
res = sorted(con.values(), reverse=True)
second_max = res[1]
for key, val in con.items():
if val == second_max:
print("Second most repeated word:", key)
return
if __name__ == "__main__":
A = []
n = int(input("Enter the size of the List: "))
for _ in range(n):
A.append(input("Enter word: "))
secondrepeatation(A)
ผลลัพธ์
Enter the size of the List: 4 Enter word: aa Enter word: bb Enter word: aa Enter word: cc Second most repeated word: bb