Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Từ lặp lại thứ hai trong sequence trong Python


Cho chuỗi, nhiệm vụ tìm từ lặp lại thứ hai. Dùng Counter(iterator) tạo dictionary key=từ, value=tần suất.

Thuật toán

Bước 1: Tạo list do người dùng định nghĩa.
Bước 2: Chuyển list thành dictionary.
Bước 3: Lấy values và sắp xếp giảm dần.
Bước 4: Phần tử thứ hai là giá trị lớn thứ hai.
Bước 5: Duyệt lại dictionary in key có value bằng giá trị lớn thứ hai.

Ví dụ mã

# In từ lặp lại thứ hai trong sequence Python
from collections import Counter

def secondrepeatation(A):
    # Chuyển list thành dictionary
    con = Counter(A)
    res = sorted(con.values(), reverse=True)
    maxi = res[1]
    for (key, val) in con.items():
        if val == maxi:
            print("Second most repeated word ::>", key)
            return

# Driver program
if __name__ == "__main__":
    A = list()
    n = int(input("Enter the size of the List ::"))
    print("Enter the word ::")
    for i in range(int(n)):
        k = input("")
        A.append(k)
    secondrepeatation(A)

Kết quả

Enter the size of the List ::4
Enter the word ::
aa
bb
aa
cc
Second most repeated word ::> bb