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

หาคำที่ซ้ำอันดับ 2 ในลำดับด้วย Python Counter


หาคำที่มีความถี่เป็นอันดับ 2 มากที่สุดในลิสต์คำ โดยใช้ Counter เรียงค่าความถี่

อัลกอริทึม

  1. สร้าง Counter จากลิสต์คำ
  2. เรียงค่าความถี่มากไปน้อย
  3. หาค่าอันดับ 2 (index 1)
  4. หา 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